staticmethod classmethod property

多态

  • 接口重用,一种接口,多种实现 ,必须满足2个条件
    • 继承 (多态一定是发生在子类和父类之间)
    • 重写 (子类需要重写父类的方法)
class Animal():
    def cry(self, obj):
        obj.cry()


class dog(Animal):
    def cry(self):
        print("小狗 汪汪汪...")


class cat(Animal):
    def cry(self):
        print("小猫 喵喵喵...")

animal = Animal()
animal.cry(dog())
animal.cry(cat())

  

静态方法:

  • 静态方法需要使用@staticmethod修饰 ;
  • 静态方法不能传入self参数   ;
  • 只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性
  • 静态方法属于类的一个函数(可以通过class.staticMethod()  和 obj.staticMethod()  进行call );

类方法: 

  • 类方法需要用 @classmethod  类进行装饰 ;
  • 类方法中需要至少1个"cls" 参数
  • 只能访问类变量,不能访问实例变量 ;
  • 类方法推荐使用类名直接调用,当然也可以使用实例对象来调用(不推荐) ;

属性方法: @property

  • 把一个方法变成静态属性,当类有一个私有属性的时候可以通过get 和 set 方法来进行获取和修改

@property
def getP_att(self):
print("getter 私有属性__p_att: %s" % self.__p_att)
return self.__p_att

@getP_att.setter
def getP_att(self, var):
print("setter 私有属性__p_att: %s" % self.__p_att)
self.__p_att = var

@getP_att.deleter
def getP_att(self):
print(" %s deleter 私有属性__p_att ;"% self)
del self.__p_att

  

原文地址:https://www.cnblogs.com/linbo3168/p/15202687.html