python 静态方法与类方法

来源:互联网 发布:淘宝旺铺基础版店招 编辑:程序博客网 时间:2024/05/23 13:37

1. 对象方法有self参数,类方法有cls参数,静态方法是不需要这些附加参数的。

2. @staticmethod和@classmethod都是用来定义静态函数的。

相同点:

都不用实例化类,可以直接用类名来调用其相关属性。

不同点:

@classmethod的第一个参数是cls,因此可以访问类变量,或是用作类厂。

@staticmethod只是自身代码在类里面,对类的其它再无相关。

3. 一般情况下用@classmethod,@staticmethod只适用于不想定义全局函数的情况。

4. 类方法可以访问per-class的数据。举个不实际的例子:

[python] view plaincopy
  1. >>> class Named(object):  
  2. ...     @classmethod  
  3. ...     def name(cls):  
  4. ...             return cls.__name__  
  5. ...   
  6. >>> class Sub(Named):  
  7. ...     pass  
  8. ...   
  9. >>> obj = Sub()  
  10. >>> obj.name()  
  11. 'Sub'  
[python] view plaincopy
  1. ------------------------------------------------------------------------------------------------------------------------------  
[python] view plaincopy
  1. 第一种方式(staticmethod):  
  2.   
  3. >>> class Foo:  
  4.         str = "sample."  
  5.   
  6.         def bar():  
  7.             print Foo.str  
  8.   
  9.         bar = staticmethod(bar)  
  10.   
  11.   
  12. >>> Foo.bar()  
  13. sample.  
  14.   
  15. 第二种方式(classmethod):  
  16.   
  17. >>> class Foo:  
  18.         str = "sample."  
  19.   
  20.         def bar(cls):  
  21.             print cls.str  
  22.   
  23.         bar = classmethod(bar)  
  24.   
  25. >>> Foo.bar()  
  26. sample.  
  27.   
  28. ---------------------------------------------------------------  
  29.   
  30. 上面的代码我们还可以写的更简便些:  
  31.   
  32. >>> class Foo:  
  33.         str = "sample."  
  34.  
  35.         @staticmethod  
  36.         def bar():  
  37.             print Foo.str  
  38.   
  39. >>> Foo.bar()  
  40. sample.  
  41.   
  42. 或者  
  43.   
  44. >>> class Foo:  
  45.         str = "sample."  
  46.  
  47.         @classmethod  
  48.         def bar(cls):  
  49.             print cls.str  
  50.   
  51. >>> Foo.bar()  
  52. sample   
  53.   
  54. <p> </p>