Raf*_*ini 21 python decorator instance
我有一个类在他们的函数上有一个沉闷的重复模式,我想把这个模式变成一个装饰器.但问题是这个装饰器必须访问当前实例的一些属性,所以我想把它变成这个类中的方法.我遇到了一些问题.
所以,这与我想要的类似:
class DullRepetitiveClass:
def __init__(self, nicevariable):
self.nicevariable = nicevariable
def mydecorator(self, myfunction):
def call(*args, **kwargs):
print "Hi! The value of nicevariable is %s"%(self.nicevariable,)
return myfunction(*args, **kwargs)
return call
@mydecorator #Here, comment (1) below.
def somemethod(self, x):
return x + 1
Run Code Online (Sandbox Code Playgroud)
(1)这是问题所在.我想用这个DullRepetitiveClass.mydecorator方法来装饰somemethod方法.但我不知道如何使用当前实例中的方法作为装饰器.
有一个简单的方法吗?
编辑:好的,答案很明显.正如Sven所说,装饰器本身只是改变了方法.该方法本身应该处理与实例有关的所有事情:
def mydecorator(method):
def call(self, *args, **kwargs):
print "Hi! The value of nicevariable is %s"%(self.nicevariable,)
return method(self, *args, **kwargs)
return call
class DullRepetitiveClass:
def __init__(self, nicevariable):
self.nicevariable = nicevariable
@mydecorator
def somemethod(self, x):
return x + 1
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 15
装饰器只获得一个参数 - 它装饰的函数或方法.它不会作为self参数传递实例- 在调用decorator时,甚至没有创建类,更不用说类的实例了.该实例将作为第一个参数传递给装饰函数,因此您应该self在参数列表中包含第一个参数call().
我没有看到在类范围中包含装饰器的必要性.您可以这样做,但您也可以在模块范围内使用它.
| 归档时间: |
|
| 查看次数: |
2844 次 |
| 最近记录: |