2014-07-14 37 views
2

是否可以訪問綁定方法綁定的對象?如何從綁定方法獲取對實例的引用?

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) 
+0

未來的讀者:否則在python <2.6,'__self__'中使用'im_self'。 – wim

回答

2

綁定方法有__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中有更詳細的描述。

相關問題