创建可以看到当前类方法的装饰器
您可以在类中创建一个可以看到类方法和变量的装饰器吗?
这里的装饰器没有看到: 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)
Can you create a decorator inside a class that will see the classes methods and variables?
The decorator here doesnt see: 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有真正需要将此装饰器实现为类,也无需在
Foo
类的定义中实现它。以下内容就足够了:使用该装饰器似乎可行:
There's no real need to implement this decorator as a class, and there's no need to implement it inside the definition of the
Foo
class. The following will suffice:Using that decorator seems to work:
您可以将其作为一个类,但需要使用描述符协议
当您想要使用 __call__ 方法用类实例装饰类方法时,始终需要使用描述符。这样做的原因是,只会传入一个 self ,它引用装饰类的实例,而不是被装饰方法的实例。
You can have it be a class but you need to use the descriptor protocol
You always need to use a descriptor when you want to decorate class methods with a class instance using the
__call__
method. The reason for this is that there will only be oneself
passed in which refers to the instance of the decorating class and not the instance of the decorated method.我之前的回答是仓促的。如果您想编写一个装饰器,那么您应该使用
functools
模块中的wraps
。它会为您处理困难的事情。定义 canRun 装饰器的正确方法是:
canRun 函数应该在类外部定义。
My previous answer was made in haste. If you're wanting to write a decorator you should really use
wraps
from thefunctools
module. It takes care of the hard stuff for you.A proper way to define the canRun decorator is:
The canRun function should be defined outside of the class.