python私有成员与公有成员

python并没有对私有成员提供严格的访问保护机制。

  • 在定义类的成员时,如果成员名以两个下划线“__”或更多下划线开头而不以两个或更多下划线结束则表示是私有成员。
  • 私有成员在类的外部不能直接访问,需要通过调用对象的公开成员方法来访问,也可以通过Python支持的特殊方式来访问。
 1 class A:
 2     def __init__(self, value1 = 0, value2 = 0):
 3         self._value1 = value1
 4         self.__value2 = value2
 5     def setValue(self, value1, value2):
 6         self._value1 = value1
 7         self.__value2 = value2
 8     def show(self):
 9         print(self._value1)
10         print(self.__value2)
11 
12 >>> a = A()
13 >>> a._value1
14 0
15 >>> a._A__value2         # 在外部访问对象的私有数据成员
16 0
在Python中,以下划线开头的变量名和方法名有特殊的含义,尤其是在类的定义中。
  • _xxx:受保护成员,不能用"from module import *"导入
  • __xxx__:系统定义的特殊成员
  • __xxx:私有成员,只有类对象自己能访问,子类对象不能直接访问到这个成员,但在对象外部可以通过“对象名._类名__xxx”这样的特殊方式来访问
Python中不存在严格意义上的私有成员。
 1 class Fruit:
 2     def __init__(self):
 3         self.__color = 'Red'
 4         self.price = 1
 5 >>> apple = Fruit()
 6 >>> apple.price                               # 显示对象公开数据成员的值
 7 1
 8 >>> print(apple.price, apple._Fruit__color)   # 显示对象私有数据成员的值
 9 1 Red
10 >>> apple.price = 2                           # 修改对象公开数据成员的值
11 >>> apple._Fruit__color = "Blue"              # 修改对象私有数据成员的值
12 >>> print(apple.price, apple._Fruit__color)
13 2 Blue
14 >>> print(apple.__color)                      # 不能直接访问对象的私有数据成员,出错
15 AttributeError:Fruit instance has no attribute '__color'

在程序中,可以使用一个下划线“_”来表示不关心该变量的值。

1 for _ in range(5):
2     print(3, end=' ')     # 此处的3可以为任意值,输出结果为重复5次的值。若改为print(_, end=' ');>>>0 1 2 3 4
3 3 3 3 3 3
4 >>> a, _ = divmod(60, 18) # 只关心整商,不关心余数。
5 >>> a                     # 即等价于a = 60//18
6 3

猜你喜欢

转载自www.cnblogs.com/cpl9412290130/p/9700820.html