zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Windows Server 2008 Standard Enterprise Datacenter各个版本区别
    .Net4.0并行库介绍——Cancellation Framework
    .Net4.0并行库介绍——Task
    安装VS组件提示“所选驱动不再有效。继续安装之前,请先检查安装路径的设置。”要怎么办?
    Activex 数字签名
    要使用C#实现一个ActiveX控件
    Win8系统108个运行命令 你能记住多少?
    解决 Operation must use an updateable query
    HTTP Error 404.2
    win7 系统装SQLServer2000 成功
  • 原文地址:https://www.cnblogs.com/cpl9412290130/p/9700820.html
Copyright © 2011-2022 走看看