python函数与方法的区别_Python 3中'函数','方法'和'绑定方法'有什么区别?

1586010002-jmsa.png

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

>>> class A():

... def f(): pass

...

>>> A.f

>>> A().f

>>> set.union

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 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值