这是一种单行方法修饰器,它似乎无需修改标记为只读的Callable type *的任何特殊属性即可完成此工作:
# method decorator -- makes undeclared 'self' argument available to method
injectself = lambda f: lambda self: eval(f.func_code, dict(self=self))
class TestClass:
def __init__(self, thing):
self.attr = thing
@injectself
def method():
print 'in TestClass::method(): self.attr = %r' % self.attr
return 42
test = TestClass("attribute's value")
ret = test.method()
print 'return value:', ret
# output:
# in TestClass::method(): self.attr = "attribute's value"
# return value: 42
需要注意的是,除非你采取预防措施,以防止它,一个副作用的的eval()
功能可能是它增加了一些条目- 如在参考__builtin__
下键模块__builtins__
-自动将dict
传递给它。
@kendall:根据您的评论,如何将其与容器类中的方法一起使用(但暂时不考虑其他变量的注入)-以下是您正在做的事情吗?对于我来说,很难理解框架和用户编写的内容之间是如何划分的。对我来说,这听起来像是一个有趣的设计模式。
# method decorator -- makes undeclared 'self' argument available to method
injectself = lambda f: lambda self: eval(f.func_code, dict(self=self))
class methodclass:
def __call__():
print 'in methodclass::__call__(): self.attr = %r' % self.attr
return 42
class TestClass:
def __init__(self, thing):
self.attr = thing
method = injectself(methodclass.__call__)
test = TestClass("attribute's value")
ret = test.method()
print 'return value:', ret
# output
# in methodclass::__call__(): self.attr = "attribute's value"
# return value: 42