ITPub博客

首页 > IT职业 > IT职场 > python双下划线有什么用

python双下划线有什么用

IT职场 作者:jerrysun 时间:2021-09-11 09:57:23 0 删除 编辑

1、说明

双下划线开头表示私有,但这不是Python设计双下划线开头的初衷和目的,Python设计此的真正目的仅仅是为了避免子类覆盖父类的方法。

2、实例

class A(object):
    
    def __method(self):
        print("I'm a method in class A")
 
    def method_x(self):
        print("I'm another method in class An")
 
    def method(self):
        self.__method()
        self.method_x()
 
class B(A):
    
    def __method(self):
        print("I'm a method in class B")
 
    def method_x(self):
        print("I'm another method in class Bn")
 
 
if __name__ == '__main__':
    
    print("situation 1:")
    a = A()
    a.method()
 
    b = B()
    b.method()
 
    print("situation 2:")
    # a.__method()
    a._A__method()

以上就是python双下划线的作用,希望对大家有所帮助。更多Python学习指路:python常见问题

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/151/viewspace-2830296/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-09-29

  • 博文量
    122
  • 访问量
    16191