一、

今天读代码的时候发现Python的class定义中提及了@classmethod修饰符,然后查阅了一些材料一探究竟,先做个总结吧。

在 Python中提到 classmethod 就要提到 staticmethod,不是因为二者有什么关系,而是为了让用户区分以便更清楚地写代码。在C++中,我们了解直接通过类名访问的函数称为类的静态函 数,即static修饰的函数,可见C++中classmethod和staticmethod是一个概念。
那么python中二者有什么区别呢?先来看下二者如何在python代码中声明:
  • class MyClass:
  •     ...
  •     
  •     @classmethod  # classmethod的修饰符
  •     def class_method(cls, arg1, arg2...):
  •         ...
  •     @staticmethod  # staticmethod的修饰符
  •     def static_method(arg1, arg2...):
  •         ...
  • 对于classmethod的参数,需要隐式地传递类名,而staticmethod参数中则不需要传递类名,其实这就是二者最大的区别。
    二者都可以通过类名或者类实例对象来调用,因为强调的是classmethod和staticmethod,所以在写代码的时候最好使用类名,良好的编程习惯吧。
    对于staticmethod就是为了要在类中定义而设置的,一般来说很少这样使用,可以使用模块级(module-level)的函数来替代它。既然要把它定义在类中,想必有作者的考虑。
    对于classmethod,可以通过子类来进行重定义。
    提到类级别的函数,也顺带提及类级别的变量
  • class MyClass:
  •     
  •     i = 123 # class-level variable
  •     
  •     def __init__(self):
  •         ...
  •     ...
  • 为了清晰地区分上面两个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/

    相关文章:

    • 2022-12-23
    • 2021-07-15
    • 2021-12-03
    • 2022-12-23
    • 2021-12-02
    • 2021-12-29
    • 2021-05-15
    猜你喜欢
    • 2022-12-23
    • 2022-12-23
    • 2021-08-26
    • 2021-10-23
    • 2022-12-23
    • 2022-12-23
    • 2022-12-23
    相关资源
    相似解决方案