Python @staticmethod, @classmethod, @property

@staticmethod, @classmethod, @property 用法及作用

class Foo(object) :
    def __init__(self) : 
        self._name = "property test"
        print "init"

    def test(self) : 
        print "class method"

    @property
    def name(self) : 
        return self._name

    @staticmethod
    def staticfun() : 
        print "static method function"

    @classmethod
    def classfun(cls) : 
        print "class method function"

if '__main__' == __name__ :  
    Foo.staticfun()
    Foo.classfun()

    f = Foo()
    print f.name
    f.test()
  • @staticmethod : 静态方法
  • @classmethod : 类方法
  • @property : 将函数以类成员属性方式调用

在C++中,通过类名直接调用的函数称为静态方法,可见@staticmethod和@classmethod没有区别,当然还是有些细微的不同,@classmethod的参数,需要隐式的传递类名.

当然,与C++中是不同的,C++中的成员方法,是不能通过类的实例化对象调用的,直接通过类名调用.

原文地址:https://www.cnblogs.com/naray/p/4422602.html