python, 私有属性详解
作者:互联网
class Animal: __ORE= 'Animal ore' @classmethod def getore(cls): # 由于是私有属性,所以此处的cls.__ORE已经被解释器替换成cls._Animal_ORE print('class: {}\tclassORE: {}'.format(cls.__name__, cls.__ORE)) class Pig(Animal): __ORE='Pig ore' # @classmethod # def getore(cls): # print('class: {}\tclassORE: {}'.format(cls.__name__, cls.__ORE)) p=Pig() p.getore() # 得到是Animal的__ORE print(Pig.__dict__) # 只展现在自己类内部定义的属性,不会展现父类属性 # print(Animal.__dict__)
下面将父类的getore方法override
class Animal: __ORE= 'Animal ore' @classmethod def getore(cls): # 由于是私有属性,所以此处的cls.__ORE已经被解释器替换成cls._Animal_ORE print('class: {}\tclassORE: {}'.format(cls.__name__, cls.__ORE)) class Pig(Animal): __ORE='Pig ore' @classmethod def getore(cls): print('class: {}\tclassORE: {}'.format(cls.__name__, cls.__ORE)) p=Pig() p.getore() # 得到是Animal的__ORE print(Pig.__dict__) # 只展现在自己类内部定义的属性,不会展现父类属性 # print(Animal.__dict__)
getore获取到的是Pig的私有属性了
做一个深入的实验
class Animal: __ORE= 'Animal ore' @classmethod def getore(cls): # 由于是私有属性,所以此处的cls.__ORE已经被解释器替换成cls._Animal_ORE print('class: {}\tclassORE: {}'.format(cls.__name__, cls.__ORE)) class Pig(Animal): __ORE='Pig ore' _Animal__ORE='Pig phony ORE' # @classmethod # def getore(cls): # print('class: {}\tclassORE: {}'.format(cls.__name__, cls.__ORE)) p=Pig() p.getore() # 得到是Animal的__ORE print(Pig.__dict__) # 只展现在自己类内部定义的属性,不会展现父类属性 # print(Animal.__dict__)
自定义一个跟替换后同名的属性于Pig类中
标签:__,.__,python,Pig,私有,详解,Animal,ORE,cls 来源: https://www.cnblogs.com/dissipate/p/13767173.html