_
私有属性或方法, 该方法或属性不应该在外部去调用(不建议在类的外面直接调用这个方法,但是也可以调用)
__
避免子类覆盖其内容
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中的_和_____的全部内容,更多相关Python中内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复