下面的类方法有什么区别?

是不是一个是静态的,另一个不是?

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的调用将抛出一个异常,表示不接受self参数,Python运行时将自动传递给它。

如果你想在Python类中创建一个静态方法,用staticmethod装饰器来装饰它。

Class Test(Object):
  @staticmethod
  def method_two():
    print "Called method_two"

Test.method_two()

其他回答

这是一个错误。

首先,第一行应该是这样的(注意大写)

class Test(object):

当你调用一个类的方法时,它将自己作为第一个参数(因此命名为self), method_two会给出这个错误

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

绑定方法=实例方法

解绑定方法=静态方法。

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'。

>>> class Class(object):
...     def __init__(self):
...         self.i = 0
...     def instance_method(self):
...         self.i += 1
...         print self.i
...     c = 0
...     @classmethod
...     def class_method(cls):
...         cls.c += 1
...         print cls.c
...     @staticmethod
...     def static_method(s):
...         s += 1
...         print s
... 
>>> a = Class()
>>> a.class_method()
1
>>> Class.class_method()    # The class shares this value across instances
2
>>> a.instance_method()
1
>>> Class.instance_method() # The class cannot use an instance method
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method instance_method() must be called with Class instance as first argument (got nothing instead)
>>> Class.instance_method(a)
2
>>> b = 0
>>> a.static_method(b)
1
>>> a.static_method(a.c) # Static method does not have direct access to 
>>>                      # class or instance properties.
3
>>> Class.c        # a.c above was passed by value and not by reference.
2
>>> a.c
2
>>> a.c = 5        # The connection between the instance
>>> Class.c        # and its class is weak as seen here.
2
>>> Class.class_method()
3
>>> a.c
5

对method_two的调用将抛出一个异常,表示不接受self参数,Python运行时将自动传递给它。

如果你想在Python类中创建一个静态方法,用staticmethod装饰器来装饰它。

Class Test(Object):
  @staticmethod
  def method_two():
    print "Called method_two"

Test.method_two()