gpt4 book ai didi

python - 创建可以看到当前类方法的装饰器

转载 作者:太空狗 更新时间:2023-10-30 02:23:29 24 4
gpt4 key购买 nike

你能在类中创建一个装饰器来查看类方法和变量吗?

这里的装饰器看不到:self.longcondition()

class Foo:
def __init__(self, name):
self.name = name

# decorator that will see the self.longcondition ???
class canRun(object):
def __init__(self, f):
self.f = f

def __call__(self, *args):
if self.longcondition(): # <-------- ???
self.f(*args)

# this is supposed to be a very long condition :)
def longcondition(self):
return isinstance(self.name, str)

@canRun # <------
def run(self, times):
for i in xrange(times):
print "%s. run... %s" % (i, self.name)

最佳答案

没有必要将这个装饰器作为一个类来实现,也没有必要在 Foo 类的定义中实现它。以下内容就足够了:

def canRun(meth):
def decorated_meth(self, *args, **kwargs):
if self.longcondition():
print 'Can run'
return meth(self, *args, **kwargs)
else:
print 'Cannot run'
return None
return decorated_meth

使用那个装饰器似乎可行:

>>> Foo('hello').run(5)
Can run
0. run... hello
1. run... hello
2. run... hello
3. run... hello
4. run... hello
>>> Foo(123).run(5)
Cannot run

关于python - 创建可以看到当前类方法的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3704392/

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