Python中的受保护变量
先决条件: Python中的下划线 (_)
变量是我们分配给内存位置的标识符,用于在计算机程序中保存值。变量是程序中的命名存储位置。根据访问规范,变量在一个类中可以是公共的、受保护的和私有的。
受保护的变量是可以在类中访问的类的那些数据成员以及从该类派生的类。在Python中,不存在“公共”实例变量。但是,我们使用下划线“_”符号来确定类中数据成员的访问控制。任何以下划线为前缀的成员都应被视为 API 或任何Python代码的非公共部分,无论它是函数、方法还是数据成员。
示例 1:
# program to illustrate protected
# data members in a class
# Defining a class
class Geek:
# protected data members
_name = "R2J"
_roll = 1706256
# public member function
def displayNameAndRoll(self):
# accessing protected data members
print("Name: ", self._name)
print("Roll: ", self._roll)
# creating objects of the class
obj = Geek()
# calling public member
# functions of the class
obj.displayNameAndRoll()
输出:
Name: R2J
Roll: 1706256
示例 2:继承期间
# program to illustrate protected
# data members in a class
# super class
class Shape:
# constructor
def __init__(self, length, breadth):
self._length = length
self._breadth = breadth
# public member function
def displaySides(self):
# accessing protected data members
print("Length: ", self._length)
print("Breadth: ", self._breadth)
# derived class
class Rectangle(Shape):
# constructor
def __init__(self, length, breadth):
# Calling the constructor of
# Super class
Shape.__init__(self, length, breadth)
# public member function
def calculateArea(self):
# accessing protected data members of super class
print("Area: ", self._length * self._breadth)
# creating objects of the
# derived class
obj = Rectangle(80, 50)
# calling derived member
# functions of the class
obj.displaySides()
# calling public member
# functions of the class
obj.calculateArea()
输出:
Length: 80
Breadth: 50
Area: 4000
在上面的示例中,超类Shape
的受保护变量_length
和_breadth
在类中通过成员函数displaySides()
访问,并且可以从派生自Shape
类的类Rectangle
访问。 Rectangle
类的成员函数calculateArea()
访问超类Shape
的受保护数据成员_length
和_breadth
来计算矩形的面积。