# 有时候我们需要一些private属性,但是python在类中并没有做访问控制 # 我们遵循一些基本的编程规则来让大家达成共识 # 1.别碰单下划线开头的东西 class A: def __init__(self): self._internal=0 self.public = 1 def public_method(self): print("It's a public method") def _private_method(self): print("It's a private method") # 这是人为制约的标准,请务必遵守它,访问_变量的行为是粗鲁的 # 如果你想要让某个方法在继承时不被覆写,那么可以使用__ # 在继承时,__开头的方法会被重整成_类名__方法名的形式 class B: def __init__(self): self.__private=0 def __private_method(self): print("这是B的私有方法") def public_method(self): print("这是B的公有方法") class C(B): def __init__(self): super().__init__() self.__private = 1 # 重新定义C的方法 def __private_method(self): print("这是C的私有方法") # 可以看到B的私有方法没有被覆写,而是被重整成了_B__private_method def public_method(self): self.__private_method() super()._B__private_method() c = C() c.public_method() # 总结,如果只是私有名称,那么可以使用_;如果私有名称还需要对子类隐藏,那就使用__ # 在与保留关键字冲突时,可以使用 命名_ 的方式来避免名称冲突同时与私有数据区分开