您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在不明确接受的情况下进入Python方法

如何在不明确接受的情况下进入Python方法

这是一种单行方法修饰器,它似乎无需修改标记为只读的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
python 2022/1/1 18:37:04 有393人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶