__x will automatically deform to _ class name __x normal condition
class A: def foo(self): print(‘from A‘) def test(self): self.foo()class B(A): def foo(self): print(‘from B‘)b = B()b.test()# from B
To define Foo as a private
class A: def __foo(self): #双下线私有属性在定义时就变形为_A__fa print(‘from A‘) def test(self): self.__foo() #调用变形后的私有属性对象,即_A__faclass B(A): def __foo(self): print(‘from B‘)b = B()b.test()# from A
Principle: The __x private property of the parent class has been transformed to the parent class __x when defined, and the subclass can inherit this property, but cannot overwrite it. So the self of Self.__foo in test () is already bound to the parent class, and __foo () of the subclass cannot be overwritten.
class A: def __foo(self): #双下线私有属性在定义时就变形为_A__fa print(‘from A‘) def test(self): self.__foo() #调用变形后的私有属性对象,即_A__faclass B(A): def __foo(self): print(‘from B‘)b = B()b._A__foo()# from A
Disadvantages of Python's private properties
This distortion does not really restrict directly accessing properties from the outside
class A: def __foo(self): print(‘from A‘) def test(self): self.__foo()a = A()a._A__foo()
Python-Private properties (variants of double downline)