下面的类方法有什么区别?
是不是一个是静态的,另一个不是?
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()
下面的类方法有什么区别?
是不是一个是静态的,另一个不是?
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()
当前回答
Method_two不能工作,因为你定义了一个成员函数,但没有告诉它这个函数是什么成员。如果你执行最后一行,你会得到:
>>> a_test.method_two()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given)
如果你为一个类定义成员函数,第一个参数必须总是'self'。
其他回答
method_two的定义无效。当你调用method_two时,你会得到TypeError: method_two()接受0个位置参数,但1个是由解释器给出的。
当您像a_test.method_two()那样调用实例方法时,它是一个有界函数。它自动接受指向Test实例的self作为第一个参数。通过self参数,实例方法可以自由地访问和修改同一对象上的属性。
The second one won't work because when you call it like that python internally tries to call it with the a_test instance as the first argument, but your method_two doesn't accept any arguments, so it wont work, you'll get a runtime error. If you want the equivalent of a static method you can use a class method. There's much less need for class methods in Python than static methods in languages like Java or C#. Most often the best solution is to use a method in the module, outside a class definition, those work more efficiently than class methods.
请阅读Guido First Class的文档,清楚地解释了Unbound, Bound方法是如何诞生的。
当调用类成员时,Python自动使用对象引用作为第一个形参。变量self实际上没有任何意义,它只是一种编码约定。如果你愿意,可以叫它滴水怪。也就是说,对method_two的调用将引发TypeError,因为Python会自动尝试将一个参数(对其父对象的引用)传递给一个定义为没有参数的方法。
为了让它工作,你可以把这个附加到你的类定义:
method_two = staticmethod(method_two)
或者您可以使用@staticmethod函数装饰器。
绑定方法=实例方法
解绑定方法=静态方法。