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

Python中类方法的差异:绑定,未绑定和静态

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

Python中类方法的差异:绑定,未绑定和静态

在Python,有区别绑定和未绑定的方法。

基本上,是调用成员函数(如

method_one
),绑定函数

a_test.method_one()

被翻译成

Test.method_one(a_test)

即对未绑定方法的调用。因此,呼叫你的版本method_two将失败,并显示TypeError

>>> a_test = Test() >>> a_test.method_two()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: method_two() takes no arguments (1 given) 

你可以使用装饰器更改方法的行为

class Test(object):    def method_one(self):        print "Called method_one"    @staticmethod    def method_two():        print "Called method two"

装饰器告诉内置默认元类type(一个类的类,请参见此问题)不为创建绑定方法method_two。

现在,你可以直接在实例或类上调用静态方法:

>>> a_test = Test()>>> a_test.method_one()Called method_one>>> a_test.method_two()Called method_two>>> Test.method_two()Called method_two


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

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

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