在属性和方法名称前加"__"这个属性和方法就变成了私有成员,私有成员在外部无法直接调用
class C():
def __init__(self):
self.name = "C"
self.__age = 18
def __fn4(self):
print("fn4")
cc = C()
print(cc.age) # AttributeError: ‘C‘ object has no attribute ‘age‘
print(cc.__age) # AttributeError: ‘C‘ object has no attribute ‘__age‘
cc.fn4() # AttributeError: ‘C‘ object has no attribute ‘fn4‘
cc.__fn4() # AttributeError: ‘C‘ object has no attribute ‘__fn4‘
提供公有的getter、setter方法
class C():
def __init__(self):
self.name = "C"
self.__age = 18
def __fn4(self):
print("fn4")
def get_age(self):
return self.__age
def set_age(self, new_age):
self.__age = new_age
cc = C()
print(cc.get_age()) # 18
cc.set_age(25)
print(cc.get_age()) # 25
原文:https://www.cnblogs.com/liuxuelin/p/14295933.html