在Python,有区别绑定和未绑定的方法。
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