Python - 公共、受保护、私有成员

2023-09-17 22:17:40

经典的面向对象语言(如 C++ 和 Java)通过公共、私有和受保护的关键字控制对类资源的访问。class的私有成员被拒绝从类外部的环境进行访问。它们只能从类内部处理。

Public Members

公共成员(通常是在类中声明的方法)可以从类外部访问。调用公共方法需要同一类的对象。 私有实例变量和公共方法的这种安排保证了数据封装的原则。

默认情况下,Python 类中的所有成员都是公共的。可以从类环境外部访问任何成员。

示例: Public Attributes

class Student:
    schoolName = 'XYZ School' # class attribute
    def __init__(self, name, age):
        self.name=name # instance attribute
        self.age=age # instance attribute

您可以访问Student类的属性,也可以修改其值,如下所示。

示例: Access Public Members

std = Student("Steve", 25)
print(std.schoolName)  #'XYZ School'
print(std.name)  #'Steve'
std.age = 20
print(std.age)

受保护的成员

类的受保护成员可以从类内部访问,也可用于其子类。 不允许其他环境访问它。这使父类的特定资源可以由子类继承。

Python 保护实例变量的约定是向其添加前缀 _(单个下划线)。 这有效地防止了它被访问,除非它来自子类中。

示例: Protected Attributes

class Student:
    _schoolName = 'XYZ School' # protected class attribute
    
    def __init__(self, name, age):
        self._name=name  # protected instance attribute
        self._age=age # protected instance attribute

事实上,这不会阻止实例变量访问或修改实例。您仍然可以执行以下操作:

示例: Access Protected Members

std = Student("Swati", 25)
print(std._name)  #'Swati'
std._name = 'Dipa'
print(std._name)  #'Dipa'

但是,您可以使用property decorator定义属性并使其受到保护,如下所示。

示例: Protected Attributes

class Student:
	def __init__(self,name):
		self._name = name
	@property
	def name(self):
		return self._name
	@name.setter
	def name(self,newname):
		self._name = newname

上面,@property装饰器用于将name()方法作为属性,并将装饰器@name.setter name()方法的另一个重载作为属性 setter 方法。现在,_name受到保护。

示例: Access Protected Members

std = Student("Swati")
print(std.name)  #'Swati'
std.name = 'Dipa'
print(std.name)  #'Dipa'
print(std._name) #'Dipa'

上面,我们使用std.name属性来修改_name属性。但是,它仍然可以在Python中访问。 因此,负责任的程序员将避免访问和修改以类外_为前缀的实例变量。

Private Members

Python 没有任何机制可以有效地限制对任何实例变量或方法的访问。Python 规定了在变量/方法名称前面加上单下划线或双下划线的约定,以模拟受保护访问说明符和专用访问说明符的行为。

以变量为前缀的双下划线__使其成为私有的。 它强烈建议不要从课堂外触摸它。任何这样做的尝试都将导致属性错误:

示例: Private Attributes

class Student:
    __schoolName = 'XYZ School' # private class attribute
    def __init__(self, name, age):
        self.__name=name  # private instance attribute
        self.__salary=age # private instance attribute
    def __display(self):  # private method
	    print('This is private method.')
std = Student("Bill", 25)
print(std.__schoolName) #AttributeError
print(std.__name)   #AttributeError
print(std.__display())  #AttributeError

Python 执行私有变量的名称重整。每个带有双下划线的成员都将更改为 _object._class__variable 。因此,仍然可以从类外访问它,但应避免这种做法。

示例: Access Private Variables

std = Student("Bill", 25)
print(std._Student__name)  #'Bill'
std._Student__name = 'Steve'
print(std._Student__name)  #'Steve'
std._Student__display()  #'This is private method.'

因此,Python 提供了公共、受保护和私有访问修饰符的概念实现,但不像其他语言,如 C#、Java C++。