Python中类方法的差异:绑定,未绑定和静态
以下类方法有什么区别?
是一个是静态的,另一个不是静态的吗?
class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()
a_test.method_one()
a_test.method_two()
-
在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