zoukankan      html  css  js  c++  java
  • day19 Python super()

    """
    super()可以帮我们执行MRO中下一个父类的⽅法,通常super()有两个使用的地方:
    1. 可以访问父类的构造方法
    2. 当子类⽅法想调用父类(MRO)中的方法
    
    """
    # 实例一
    class Foo:
        def __init__(self, a, b, c):
            self.a = a
            self.b = b
            self.c = c
            
    class Bar(Foo):
        def __init__(self, a, b, c, d):
            super().__init__(a, b, c) # 调用父类的构造方法
            self.d = d
            
    b = Bar(1, 2, 3, 4)
    print(b.__dict__)
    
    """结果:
    {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    """
    
    
    # 实例二
    class Foo:
        def func1(self):
            super().func1() # 2、 此时找的是MRO顺序中下⼀个继承类的func1()⽅法,即Ku的下一个父类Bar;报错 AttributeError: 'super' object has no attribute 'func1'
            print("我的⽼家. 就住在这个屯")
    
    class Bar:
        def func1(self):
            print("你的⽼家. 不在这个屯") # 3、 打印
    
    class Ku(Foo, Bar):
        def func1(self):
            super().func1() # 1、此时super找的是Foo
            print("他的老家. 不知道在哪个屯")
    
    class Test(Ku):
        def func2(self):
            super(Ku, self).func1()
    
    k = Ku()
    k.func1() 
    """4、result:
    你的⽼家. 不在这个屯
    我的⽼家. 就住在这个屯
    他的老家. 不知道在哪个屯
    """
    
    k1 = Foo()
    k1.func1()  
    """result:
    # AttributeError: 'super' object has no attribute 'func1'
    """
    
    test = Test()
    test.func2()
    """result:
    你的⽼家. 不在这个屯
    我的⽼家. 就住在这个屯
    """
    

      

  • 相关阅读:
    Java学习第十五章 之 Map、可变参数、Collections
    Java第十四章 之 List、Set
    Java学习第十三章 之 常用API
    通过shell终端上传下载文件
    javamail邮件发送
    linux防火墙添加例外端口shell脚本
    MySQL批量更新
    MySQL返回列名
    发现一个有意思的东西
    struts2,action方法自动执行两次
  • 原文地址:https://www.cnblogs.com/fanghongbo/p/9974770.html
Copyright © 2011-2022 走看看