【问题标题】:How can I get a reference to the instance from a bound method? [duplicate]如何从绑定方法中获取对实例的引用? [复制]
【发布时间】:2014-09-04 14:27:36
【问题描述】:

是否可以访问绑定方法绑定的对象?

class NorwegianBlue(object):

    def hello(self):
        print "Well, he's...he's, ah...probably pining for the fjords"

    def some_method(self):
        pass

thing = NorwegianBlue().some_method
the_instance = ???
thing.im_class.hello(the_instance)

【问题讨论】:

  • 对于未来的读者:在 python im_self,否则使用__self__

标签: python methods


【解决方案1】:

绑定方法有一个__self__im_self 属性:

>>> thing = NorwegianBlue().some_method
>>> thing.__self__
<__main__.NorwegianBlue object at 0x100294c50>
>>> thing.im_self
<__main__.NorwegianBlue object at 0x100294c50>

im_self 是旧名称; __self__ 是 Python 3 的名称。

您可能会发现inspect module documentation 很有帮助;它包含每个对象类型的属性表。

属性在reference Data Model documentation中有更详细的描述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-18
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 2013-01-13
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多