Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find instance of a bound method in Python?

>>> class A(object):   ...         def some(self):   ...                 pass   ...   >>> a=A()   >>> a.some   <bound method A.some of <__main__.A object at 0x7f0d6fb9c090>> 

IOW, I need to get access to "a" after being handed over only "a.some".

like image 804
mrkafk Avatar asked Jan 13 '11 11:01

mrkafk


People also ask

What is a bound method in Python?

A bound method is the one which is dependent on the instance of the class as the first argument. It passes the instance as the first argument which is used to access the variables and functions. In Python 3 and newer versions of python, all functions in the class are by default bound methods.

What is bounded method call?

If a function is an attribute of class and it is accessed via the instances, they are called bound methods. A bound method is one that has ' self ' as its first argument. Since these are dependent on the instance of classes, these are also known as instance methods.

What is current instance in Python?

An instance attribute refers to the properties of that particular object like edge of the triangle being 3, while the edge of the square can be 4. self – It is a keyword which points to the current passed instance. But it need not be passed every time while calling an instance method.

What is bounded and unbounded in Python?

So, bound mean that underlying function is bound to some instance. unbound mean that it is still bound, but only to a class. Show activity on this post. A function object is a callable object created by a function definition.


2 Answers

Starting python 2.6 you can use special attribute __self__:

>>> a.some.__self__ is a True 

im_self is phased out in py3k.

For details, see the inspect module in the Python Standard Library.

like image 174
SilentGhost Avatar answered Sep 28 '22 14:09

SilentGhost


>>> class A(object): ...   def some(self): ...     pass ... >>> a = A() >>> a <__main__.A object at 0x7fa9b965f410> >>> a.some <bound method A.some of <__main__.A object at 0x7fa9b965f410>> >>> dir(a.some) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'im_class', 'im_func', 'im_self'] >>> a.some.im_self <__main__.A object at 0x7fa9b965f410> 
like image 43
MattH Avatar answered Sep 28 '22 14:09

MattH