类里面定义的属性叫类属性,那么类属性有两种,分为:共有属性和私有属性
:
Python并没有真正的私有化支持,但可用下划线得到伪私有
私有属性定义:
- 单下滑线开头:_attr protected
- 双下划线开头:__attr private
单下滑线私有属性:外部可以直接访问;
表示的是protected(受保护的) 类型的变量,只能靠允许其本身与子类进行访问
。,如:当使用“from M import” 时,不会将一个下划线开头的对象引入。
双下滑线私有属性:外部不可直接访问
,被改名了,所以在外部无法访问,改成了__类名__attr2
只能在类内部中访问,类外部包括子类访问则报错
class Hero():
attr = 1
_attr1 = 2
__attr2 = 3
print(Hero.attr)
print(Hero._attr1)
print(Hero.__attr2)
运行结果:
1
2
Traceback (most recent call last):
File "C:/workspace/pythonTest/pythonDemo/siyou.py", line 8, in <module>
print(Hero.__attr2)
AttributeError: type object 'Hero' has no attribute '__attr2'
受保护类型子类可访问, 私有属性子类同样不可访问:
class Hero():
attr = 1
_attr1 = 2
__attr2 = 3
def fun(self): #类内部访问
print(self.attr)
print(self._attr1)
print(self.__attr2)
class Dog(Hero):
def fun(self): #继承的子类访问
print(self.attr)
print(self._attr1)
print(self.__attr2)
h=Hero()
h.fun()
d = Dog()
d.fun()
运行结果:
1
2
3
1
2
Traceback (most recent call last):
File "C:/workspace/pythonTest/pythonDemo/siyou.py", line 20, in <module>
d.fun()
File "C:/workspace/pythonTest/pythonDemo/siyou.py", line 15, in fun
print(self.__attr2)
AttributeError: 'Dog' object has no attribute '_Dog__attr2'
小结:
- 单下划线私有属性(protected): 类内部可访问,子类可访问,导入后不可访问;
- 双下划线私有属性(private):类内部可访问,子类及类外都不可访问;