可以这样写吗:
class Test(object):
def _decorator(self, foo):
foo()
@self._decorator
def bar(self):
pass
失败:@self中的self未知
我也试过了:
@Test._decorator(self)
这也失败了:测试未知
我想临时更改装饰器中的一些实例变量,然后运行装饰的方法,然后再将它们改回来。
发布于 2016-11-17 20:48:55
import functools
class Example:
def wrapper(func):
@functools.wraps(func)
def wrap(self, *args, **kwargs):
print("inside wrap")
return func(self, *args, **kwargs)
return wrap
@wrapper
def method(self):
print("METHOD")
wrapper = staticmethod(wrapper)
e = Example()
e.method()
发布于 2016-06-07 17:43:25
这是从定义在同一个类中的decorator
内部访问(并使用) self
的一种方法:
class Thing(object):
def __init__(self, name):
self.name = name
def debug_name(function):
def debug_wrapper(*args):
self = args[0]
print 'self.name = ' + self.name
print 'running function {}()'.format(function.__name__)
function(*args)
print 'self.name = ' + self.name
return debug_wrapper
@debug_name
def set_name(self, new_name):
self.name = new_name
输出(在Python 2.7.10
上测试):
>>> a = Thing('A')
>>> a.name
'A'
>>> a.set_name('B')
self.name = A
running function set_name()
self.name = B
>>> a.name
'B'
上面的例子是愚蠢的,但它是有效的。
发布于 2012-01-18 01:48:26
我在研究一个非常相似的问题时发现了这个问题。我的解决方案是将问题分成两部分。首先,您需要捕获要与类方法关联的数据。在这种情况下,handler_for会将Unix命令与该命令输出的处理程序相关联。
class OutputAnalysis(object):
"analyze the output of diagnostic commands"
def handler_for(name):
"decorator to associate a function with a command"
def wrapper(func):
func.handler_for = name
return func
return wrapper
# associate mount_p with 'mount_-p.txt'
@handler_for('mount -p')
def mount_p(self, slurped):
pass
现在我们已经将一些数据与每个类方法相关联,我们需要收集这些数据并将其存储在一个class属性中。
OutputAnalysis.cmd_handler = {}
for value in OutputAnalysis.__dict__.itervalues():
try:
OutputAnalysis.cmd_handler[value.handler_for] = value
except AttributeError:
pass
https://stackoverflow.com/questions/1263451
复制相似问题