python staticmethod和classmethod(转载)

staticmethod, classmethod 分别被称为静态方法和类方法。  

staticmethod 
基本上和一个全局函数差不多,只不过可以通过类或类的实例对象(python里只说对象总是容易产生混淆,因为什么都是对象,包括类,而实际上类实例对象才是对应静态语言中所谓对象的东西)来调用而已,不会隐式地传入任何参数。这个和静态语言中的静态方法比较像。 

classmethod 
是和一个class相关的方法,可以通过类或类实例调用,并将该class对象(不是class的实例对象)隐式的当做第一个参数传入。就这种方法可能会比较奇怪一点,不过只要你搞清楚了python里class也是个真实的存在于内存中的对象,而不是静态语言中只存在于编译期间的类型,就好办了。 

正常的方法就是和一个类的实例对象相关的方法,通过类实例对象进行调用,并将该实例对象隐式地作为第一个参数传入,这个也和其它语言比较像。 


区别: 类方法需要额外的类变量cls,当有之类继承时,调用类方法传入的类变量cls是子类,而不是父类。类方法和静态方法都可以通过类对象和类的 实例对象访问。 

静态方法:

1 class Foo:
2     str="I'm a static method"
3     def bar():
4         print(Foo.str)
5     bar=staticmethod(bar)

另一种写法:

1 class Foo:
2     str="I'm a static method"
3     @staticmethod
4     def bar():
5         print(Foo.str)

输出结果:

>>> Foo.bar()
I'm a static method.

类方法(classmethod):

写法一:

1 class Foo:
2     str="I'm a class method"
3     def bar(cls):
4         print(cls.str)
5     bar=classmethod(bar)

写法二:

1 class Foo:
2     str="I'm a class method"
3     @classmethod
4     def bar(cls):
5         print(cls.str)

运行结果:

1 >>> Foo.bar()
2 I'm a class method
原文地址:https://www.cnblogs.com/xiaoerlang/p/3462556.html