python 静态方法和类方法

1.staticmethod

类的静态方法,是类中使用staticmethod装饰的方法。可通过类本身或者类实例来调用,但是没有任何附加的隐式参数传递。方法内部调用类属性或者类方法的时候需要使用类的全名进行调用。

2. classmethod

使用 @classmethod 修饰器修饰的类型的方法,非私有的类方法可以通过类型本身或者类实例进行调用,并在调用时隐式传递类型本身作为第一个参数,该参数的形参名可以为任何合法变量名,但一般使用 cls。

3.相同点:

  • 非私有 类方法 和 类静态方法 都可以通过类实例和类本身进行调用。
  • 都可以通过继承被派生类拥有并重写。
  • 都无法在方法内部调用 类实例属性 和 类实例方法。

4.不同点:

  • 类方法 在调用时会隐式传递类型作为第一个参数;而 类静态方法 不会隐式传递任何值。
  • 类方法 的方法体中可以通过传递进来的类型实参调用该类型的 类属性 和 类方法;而 类静态方法 内部不知道任何关于类型或者类实例的信息,** 但是可以通过类型本身的类型全名调用 类属性 和 类方法。**

5.例子:

class Base(object):
    # 类属性
    ClassProperty = 0
    def __init__(self, first, second):
        # 类实例属性
        self.InstanceProperty = ""
        self.InstanceProperty1 = first
        self.instanceProperty2 = second
    def instance_method(self, msg):
        self.InstanceProperty = msg
        print self.__class__.__name__ + " instance_method" + self.InstanceProperty
    @classmethod
    def class_method(cls, msg):
        print cls.__name__ + " class_method" + msg
    @staticmethod
    def static_method(msg):
        print "static_method" + msg
    @classmethod
    def instance_factory_classmethod(cls, first):
        return cls(first, 100)
    @staticmethod
    def instance_factory_staticmethod(frist):
        return Base(frist, 200)
class DerivedA(Base):
    ClassProperty = ""
class DerivedB(Base):
    @classmethod
    def class_method(cls, msg):
        print cls.__name__ + " class_method" + msg
    @staticmethod
    def static_method(msg):
        print "Overrided static_method" + msg
if __name__ == "__main__":
    DerivedA(1, 2).instance_method(" called by instance")
    DerivedA(1, 2).class_method(" called by instance.")
    DerivedA.class_method(" called by Derived class itself.")
    DerivedA(1, 2).static_method(" called by instance.")
    DerivedA.static_method(" called by Derived class itself.")
    DerivedA.ClassProperty = "DerivedA.ClassProperty"
    print DerivedA.ClassProperty
    print '\n'
    DerivedB(1, 2).class_method(" called by instance.")
    DerivedB(1, 2).class_method(" called by instance.")
    DerivedB.class_method(" called by Derived class itself.")
    DerivedB(1, 2).static_method(" called by instance.")
    DerivedB.static_method(" called by Derived class itself.")
    print DerivedB.ClassProperty
    # 通过类静态方法获取类实例
    print isinstance(DerivedA.instance_factory_staticmethod(1), DerivedA)
    # 通过类方法后去类实例
    print isinstance(DerivedB.instance_factory_classmethod(1), DerivedB)

运行结果:

DerivedA instance_method called by instance
DerivedA class_method called by instance.
DerivedA class_method called by Derived class itself.
static_method called by instance.
static_method called by Derived class itself.
DerivedA.ClassProperty


DerivedB class_method called by instance.
DerivedB class_method called by instance.
DerivedB class_method called by Derived class itself.
Overrided static_method called by instance.
Overrided static_method called by Derived class itself.
0
False
True

你可能感兴趣的:(python 静态方法和类方法)