Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a 'function', 'method' and 'bound method' in Python 3?

I've observed at least 3 types related to functions in Python 3:

>>> class A():
...  def f(): pass
...
>>> A.f
<function A.f at 0x7fcaef304268>
>>> A().f
<bound method A.f of <__main__.A object at 0x7fcaef2fae80  
>>> set.union
<method 'union' of 'set' objects>

I'm wondering what's the difference between 'function', 'method' and 'bound method'? Is 'method' a type equivalent to 'unbound method' in Python 2?

like image 357
planetp Avatar asked Feb 03 '16 10:02

planetp


1 Answers

Is 'method' a type equivalent to 'unbound method' in Python 2?

Kind-a-sort-a. But not really. It is a method_descriptor object defined in C code. It is an unbound method, but not the kind you found in Python 2.

For Python types written C, all 'methods' are really C functions. The <method 'name' of 'type' objects> object you found is a special object you can use to call that function given an instance and further arguments, just like the function object does for custom Python classes. The object is defined in C in the PyMethodDescr_Type structure. It implements the descriptor protocol, just like functions do.

Python defines several other such descriptor types; if you use __slots__, each attribute is a dsescriptor of type member_descriptor (see the PyMemberDescr_Type structure), while classmethod, property and staticmethod are perhaps better known descriptor objects.

In Python 2, bound and unbound methods are really just one type, instancemethod (defined by the PyMethod_Type structure); it'll report as bound if the __self__ (im_self) attribute is set. In Python 3 using a function as a descriptor simply doesn't produce method objects without __self__ set; instead calling function.__get__() with no instance just returns the function again.

The only reason Python 2 returns unbound methods is to enforce a type check; the first argument must be an instance of the class (or a subclass thereof). This didn't make all that much sense for Python code that supports duck-typing, so in Python 3 the restriction was removed. However, with C code you can't use duck-typing, you still have to restrict the type, and that's why C-types still return a method_descriptor object that enforces this restriction.

like image 103
Martijn Pieters Avatar answered Sep 18 '22 11:09

Martijn Pieters