在类中封装属性名

问题:

你想封装类的实例上面的私有数据,但是Python语言并没有访问控制:

class A:
  def __init__(self):
    self._internal = 99 # An internal attribute
    self.public = 88 # A public attribute
s=A()
print s
print type(s)
print dir(s)
print s._internal
print s.public

C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a8.py
<__main__.A instance at 0x025DF4E0>
<type 'instance'>
['__doc__', '__init__', '__module__', '_internal', 'public']
99
88


class A:
  def __init__(self):
    self._internal = 99 # An internal attribute
    self.public = 88 # A public attribute
  def _internal_method(self,query):
      a=query
      return a

s=A()
print s
print type(s)
print dir(s)
print s._internal
print s.public
print s._internal_method('abc')


C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a8.py
<__main__.A instance at 0x0255F940>
<type 'instance'>
['__doc__', '__init__', '__module__', '_internal', '_internal_method', 'public']
99
88
abc


你还可能会遇到在类定义中使用两个下划线__开头的命名,比如:

class B:
  def __init__(self):
      self.__private = 0
  def __private_method(self):
      pass
  def public_method(self):
      pass
      self.__private_method()
A=B()
print A
print type(A)
print dir(A)

C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a9.py
<__main__.B instance at 0x0257F4E0>
<type 'instance'>
['_B__private', '_B__private_method', '__doc__', '__init__', '__module__', 'public_method']


使用双下划线开始会导致访问名称变成其他形式,比如,在前面的类B中,私有属性会被

分别重命名为_B__private 和  _B__private_method 。

原文地址:https://www.cnblogs.com/hzcya1995/p/13349458.html