首页 > 编程语言 > 详细

【转】Python @classmethod @staticmethod

时间:2015-03-23 17:38:15      阅读:254      评论:0      收藏:0      [点我收藏+]

一、

今天读代码的时候发现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.i = 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

二、

通常情况下,如果我们要使用一个类的方法,那我们只能将一个类实体化成一个对象,进而调用对象使用方法。

比如:

class Hello(object):
    def __init__:
        ...

    def print_hello(self):
        print "Hello"

 要用 print_hello() 就得:

hlo = Hello()
hlo.print_hello()
Hello

如果用了 @classmethod 就简单了。

 

class Hello(object):
    def __init__:
        ...

    @classmethod
    def print_hello(cls):
        print "Hello"

要用的话直接:

Hello.print_hello()
Hello

注意:@classmethod 仅仅适用于单独的,与类本身的数据结构无关函数,其实用了它的函数,与使用普通函数无异,甚至不能在参数里加入 self,如果要在其中使用类的数据结构,仍然需要将类实例化一次才可以,所以要小心使用。

 其实 Python 的 Decorator 非常有意思,更多可以去下面的网页参考一下:

http://www.python.org/dev/peps/pep-0318/

【转】Python @classmethod @staticmethod

原文:http://www.cnblogs.com/mycats/p/4360391.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!