【转】Python @classmethod @staticmethod

今天读代码的时候发现Python的class定义中提及了@classmethod修饰符,然后查阅了一些材料一探究竟,先做个总结吧。
在Python中提到 classmethod 就要提到 staticmethod,不是因为二者有什么关系,而是为了让用户区分以便更清楚地写代码。在C++中,我们了解直接通过类名访问的函数称为类的静态函数,即static修饰的函数,可见C++中classmethod和staticmethod是一个概念。
那么python中二者有什么区别呢?先来看下二者如何在python代码中声明:
  1. class MyClass:
  2.     ...
  3.     
  4.     @classmethod  # classmethod的修饰符
  5.     def class_method(cls, arg1, arg2, ...):
  6.         ...

  7.     @staticmethod  # staticmethod的修饰符
  8.     def static_method(arg1, arg2, ...):
  9.         ...
对于classmethod的参数,需要隐式地传递类名,而staticmethod参数中则不需要传递类名,其实这就是二者最大的区别。
二者都可以通过类名或者类实例对象来调用,因为强调的是classmethod和staticmethod,所以在写代码的时候最好使用类名,良好的编程习惯吧。
对于staticmethod就是为了要在类中定义而设置的,一般来说很少这样使用,可以使用模块级(module-level)的函数来替代它。既然要把它定义在类中,想必有作者的考虑。
对于classmethod,可以通过子类来进行重定义。
提到类级别的函数,也顺带提及类级别的变量
  1. class MyClass:
  2.     
  3.     i = 123 # class-level variable
  4.     
  5.     def __init__(self):
  6.         self.= 456 # object-level variable
  7.         ...
  8.     ...
为了清晰地区分上面两个i,最好的办法就是考虑到python中的一切都是object,所以i=123属于class object的,i=456属于class instance object

 

原文链接:

http://my.chinaunix.net/space.php?uid=1721137&do=blog&id=274710

 

posted on 2011-08-16 09:22  ^希望^  阅读(18846)  评论(1编辑  收藏  举报

导航