Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't bound instance methods in python reference equal?

>>> class foo(object):
...     def test(s):
...         pass
...
>>> a=foo()
>>> a.test is a.test
False
>>> print a.test
<bound method foo.test of <__main__.foo object at 0x1962b90>>
>>> print a.test
<bound method foo.test of <__main__.foo object at 0x1962b90>>
>>> hash(a.test)
28808
>>> hash(a.test)
28808
>>> id(a.test)
27940656
>>> id(a.test)
27940656
>>> b = a.test
>>> b is b
True
like image 401
Alex Roper Avatar asked Mar 21 '11 22:03

Alex Roper


People also ask

What the difference between bound and unbound methods?

When a bound method is called, it calls im_func with im_self as the first parameter followed by its calling parameters. unbound methods call the underlying function with just its calling parameters. Starting with Python 3, there are no unbound methods.

What does bound method mean 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 unbound in Python?

Methods that do not have an instance of the class as the first argument are known as unbound methods. As of Python 3.0, the unbound methods have been removed from the language. They are not bounded with any specific object of the class.

How do you compare two functions in Python?

cmp() is an in-built function in Python, it is used to compare two objects and returns value according to the given values. It does not return 'true' or 'false' instead of 'true' / 'false', it returns negative, zero or positive value based on the given input.


1 Answers

They're bound at runtime; accessing the attribute on the object rebinds the method anew each time. The reason they're different when you put both on the same line is that the first method hasn't been released by the time the second is bound.

like image 109
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 22:09

Ignacio Vazquez-Abrams