简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM