如何从绑定的方法中获取实例的引用?
有没有办法访问一个绑定了方法的对象呢?
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)
1 个回答
4
绑定方法有两个属性,分别是 __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
模块的文档,里面有关于不同对象类型的属性表,这可能会对你有帮助。
这些属性的详细描述可以在 参考 数据模型 文档 中找到。