Python中的_和__

_

私有属性或方法, 该方法或属性不应该在外部去调用(不建议在类的外面直接调用这个方法,但是也可以调用)

__

避免子类覆盖其内容

class A:

    def __method(self):
        print('This is a method from class A')

    def method(self):
        return self.__method()

class B(A):
    def __method(self):
        print('This is a method from calss B')
        
a=A()
a.method()				#This is a method from class A

b=B()
b.method()				#This is a method from class A

a.__method()			#会报错
a._A__method()			#This is a method from class A
b._A__method()			#This is a method from class A
b._B__method()			#This is a method from class B
Python中的name mangling技术	使__method变成了 _A__method   从而避免了A的子类覆盖其内容

你可能感兴趣的:(Python)