29.Python中类的私有属性和受保护属性
私有属性和受保护属性
C ++和Java之类的经典⾯向对象语⾔通过公有(public)、私有(private)和受保护(protected)的关键字来控制对类资源的访问。类的私有成员拒绝从类外部环境访问。它们只能在类的内部处理。
可从类外部访问公有成员(通常是在类中声明的⽅法)。调⽤公有⽅法需要相同类的对象。私有实例变量和公共⽅法的这种安排确保了数据封装的原理。
类的受保护成员可以从该类内部访问,也可以⽤于其⼦类。不允许其他环境访问它。这样可以使⼦类继承⽗类的特定资源。
Python没有有效限制访问任何实例变量或⽅法的机制。 Python规定了在变量/⽅法名称前加单下划线或双下划线的约定,以模拟受保护和私有访问说明符的⾏为。
默认情况下,Python类中的所有成员都是公有的。可以从类环境之外访问任何成员。
Example: Public Attributes
美工区角布置图片
class Employee:
脐带血的作用
def__init__(lf, name, sal):
lf.name=name
lf.salary=sal
可以访问员⼯类的属性,也可以修改其值,如下所⽰。
e1=Employee("Kiran",10000)
e1.salary
10000
e1.salary=20000
e1.salary
20000
Python的实例变量受保护的约定是在其上添加前缀_(单个下划线)。 这将约定防⽌对其进⾏访问, 除⾮访问来⾃⼦类。
Example: Protected Attributes
class Employee:
def__init__(lf, name, sal):
lf._name=name # protected attribute
lf._salary=sal # protected attribute
实际上,这不会阻⽌实例变量访问或修改实例。 仍然可以执⾏以下操作:
花瓶的画法e1=Employee("Swati",10000)
e1._salary
10000
e1._salary=20000
e1._salary
化妆水是什么
20000
因此,负责的程序员应避免从其类的外部访问和修改以_开头的实例变量。
hardhat
同样,在变量前加上双下划线__使其变为私有。 强烈建议不要在类外碰它。 尝试这样做会导致AttributeError:
Example: Private Attributes风雨同路人
class Employee:
def__init__(lf, name, sal):
lf.__name=name # private attribute
lf.__salary=sal # private attribute
e1=Employee("Bill",10000)
e1.__salary
---------------------------------------------------------------------------
犬冠状病毒AttributeError Traceback (most recent call last)
<ipython-input-9-d5a2eb37a52c> in <module>
阿凡达电影下载1 e1=Employee("Bill",10000)
----> 2 e1.__salary
AttributeError: 'Employee' object has no attribute '__salary'
Python执⾏私有变量的改名处理(name mangling)。 每个具有双下划线的成员将更改为_object._class__variable。 如果需要,仍然可以从类外部访问它,但是应该避免这种做法。
e1=Employee("Bill",10000)
e1._Employee__salary
10000
e1._Employee__salary=20000
e1._Employee__salary
20000