栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将函数作为类属性的赋值如何在Python中成为方法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将函数作为类属性的赋值如何在Python中成为方法?

没错,这与描述符协议有关。描述符是如何在Python中实现将接收器对象作为方法的第一个参数传递的方式。您可以从此处阅读有关Python属性查找的更多详细信息。下面以较低的级别显示了执行A.func =
func;时发生的情况;A.func:

# A.func = funcA.__dict__['func'] = func # This just sets the attribute# A.func#   The __getattribute__ method of a type object calls the __get__ method with#   None as the first parameter and the type as the second.A.__dict__['func'].__get__(None, A) # The __get__ method of a function object   # returns an unbound method object if the   # first parameter is None.a = A()# a.func()#   The __getattribute__ method of object finds an attribute on the type object#   and calls the __get__ method of it with the instance as its first parameter.a.__class__.__dict__['func'].__get__(a, a.__class__)#   This returns a bound method object that is actually just a proxy for#   inserting the object as the first parameter to the function call.

因此,是在类或实例上查找该函数,将其转换为方法,而不是将其分配给类属性。

classmethod
并且
staticmethod
只是略有不同的描述符,类方法返回绑定到类型对象的绑定方法对象,而静态方法仅返回原始函数。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611239.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号