您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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
python 2022/1/1 18:17:47 有456人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶