gpt4 book ai didi

从类到装饰器的python自变量

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:07 25 4
gpt4 key购买 nike

我正在尝试构建我的第一个装饰器并在类中实现它。

# decorator class
class Cache(object):
def __init__(self,filename,**kwargs):
self.time_ago = datetime.now() - timedelta(**kwargs)
self.filename = filename

def __call__(self,fn):
if not os.path.isfile(self.filename):
return self.cache(fn(self))

time_ago = self.time_ago
filename = self.filename
c_age = datetime.fromtimestamp(os.path.getctime(filename))
m_age = datetime.fromtimestamp(os.path.getmtime(filename))
print (c_age)
print (m_age)
print (time_ago)
if c_age < time_ago or m_age < time_ago:
return self.cache(fn(self))
else:
return self.read()

def cache(self,data):
with open(self.filename,'r+') as ef:
ef.write(data)
return ef.read()

def read(self):
f = open(self.filename,'r')
data = f.read()
f.close()
return data

我正在尝试在下面的类中调用装饰器:

class Zabb(object):

@Cache('nodes.json',minutes=1)
def getNodes(self):
return "Get Nodes"

我这样调用它:

z = Zabb()
nodes = z.getNodes()

我收到以下错误:

Traceback (most recent call last):
File "./deco.py", line 52, in <module>
nodes = z.getNodes()
TypeError: 'str' object is not callable

我即将完成这项工作。我做错了什么?

最佳答案

您需要从 __call__ 方法返回一个高阶函数(包装)。添加一个内部方法并返回它。

def __call__(self, fn):
def wrapper(*args, **kwargs): # <-- Add this wrapper
if not os.path.isfile(self.filename):
return self.cache(fn(*args, **kwargs))

time_ago = self.time_ago
filename = self.filename
c_age = datetime.fromtimestamp(os.path.getctime(filename))
m_age = datetime.fromtimestamp(os.path.getmtime(filename))
print (c_age)
print (m_age)
print (time_ago)
if c_age < time_ago or m_age < time_ago:
return self.cache(fn(*args, **kwargs))
else:
return self.read()
return wrapper # <-- Return the wrapper

关于从类到装饰器的python自变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44137608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com