实例
- 类属性中的私有变量,在字典中存储形式自动更名
- 类方法调用私有变量,其实时调用更名后的内容
- 子类调用父类私有变量时,其实是调用父类更名后的内容
- 子类调用父类的内容,一切看字典
# -*- coding: UTF-8 -*-
class Animal:
__COUNT = 100 #在字典中的表现形式为:_Animal__COUNTT:100
HEIGHT = 0
def __init__(self,age,weight,height):
self.__COUNT += 1 #等价_Animal__COUNT += 1,字典中表现为_Animal__COUNT:101,向下如此继承
self.__weight = weight
self.HEIGHT = height
@classmethod
def showcount1(cls):
print(cls.__COUNT) #根据私有属性知,等价print(cls._Animal__COUNT) == print(100)
return "class Animal __COUNT"
def showcount3(self):
print(self.__COUNT) #根据私有属性知,等价print(self._Animal__COUNT) ==print(101)
return "self Animal __COUNT += 1"
class Cat(Animal):
NAME = "CAT"
__COUNT = 200 #等价_Cat__COUNT = 200
c = Cat(3,5,15)
print(c.showcount1()) #等价:print(print(Animal__COUNT) | print(100))
print(Animal._Animal__COUNT)
print("~~~~~~~~~~~~~~~~~~~~")
print(c._Cat__COUNT,"class Cat __COUNT")
print("~~~~~~~~~~~~~~~~~~~~")
print(c.showcount3()) #等价print(self._Animal__COUNT) ==print(101)
print(c._Animal__COUNT)
print("~~~~~~~~~~~~~~~~~~~~")
print(c.__dict__)
上述实例运行结果如下,和预期效果一直:
100
class Animal __COUNT
100
~~~~~~~~~~~~~~~~~~~~
200 class Cat __COUNT
~~~~~~~~~~~~~~~~~~~~
101
self Animal __COUNT += 1
101
~~~~~~~~~~~~~~~~~~~~
{'age': 3, '_Animal__weight': 5, 'HEIGHT': 15, '_Animal__COUNT': 101}
总结继承
- 一切尽在字典中
- 公有的属性,子类和实例都可以随意访问
- 私有成员被隐藏,子类和实例不可直接访问
- 私有变量在类内的方法中,可以访问这个私有变量
属性查找顺序
- 实例的__dict__ >>类__dict__ >>父类__dict__
- 通过类.__mro__可知类属性解析顺序