1.私有变量或者私有变量外部无法访问只能在类中访问

1.1私有变量

  1. class Foo(object):
  2. def __init__(self, name, age):
  3. self.__name = name
  4. self.age = age
  5. def get_data(self):
  6. return self.__name
  7. def get_age(self):
  8. return self.age
  9. obj = Foo("武沛齐", 123)
  10. # 私有成员
  11. # print(obj.__name) # 错误,由于是私有成员,只能在类中进行使用。
  12. v2 = obj.get_data()
  13. print(v2)

1.2 私有方法

  1. class Foo(object):
  2. def get_age(self):
  3. print("公有的get_age")
  4. def __get_data(self):
  5. print("私有的__get_data方法")
  6. def proxy(self):
  7. print("公有的proxy")
  8. self.__get_data()
  9. obj = Foo()
  10. obj.get_age()
  11. obj.proxy() # __get_data()通过proxy()间接访问

2.强制从外部访问私有成员(不提倡)

  1. class Foo(object):
  2. def __init__(self):
  3. self.__num = 123
  4. self.age = 19
  5. def __msg(self):
  6. print(1234)
  7. obj = Foo()
  8. print(obj._Foo__num)
  9. obj._Foo__msg()