• 继承类构造方法使用


    1,调用未绑定的超类构造方法

    class Bird:
        def __init__(self):
            self.hungry = True
    
        def eat(self):
            if self.hungry:
                print("eee")
                self.hungry = False
            else:
                print("No,thanks!")
            # print("eat!")
    
    
    class SongBird(Bird):
        def __init__(self):
            Bird.__init__(self)
            self.sound = "squak"
    
        def sing(self):
            print (self.sound)
    
    
    sb = SongBird()
    sb.eat()

    2,使用super函数

    __metaclass__=type#super函数只在新式类中起作用
    class Bird:
        def __init__(self):
            self.hungry = True
    
        def eat(self):
            if self.hungry:
                print("eee")
                self.hungry = False
            else:
                print("No,thanks!")
            # print("eat!")
    
    
    class SongBird(Bird):
        def __init__(self):
            super(SongBird,self).__init__()
            self.sound = "squak"
    
        def sing(self):
            print (self.sound)
    
    
    sb = SongBird()
    sb.eat()

    一个类继承多个超类的情况下,只需要使用一次super函数就可以

  • 相关阅读:
    扩展欧几里得算法
    单源最短路径—Dijkstra算法
    欧拉定理,费马小定理
    欧拉函数
    Trie 字典树
    平衡树——Treap,Splay
    NOI2009 开关
    银河英雄传说
    线段树与延迟标记
    c++常见变量的极值
  • 原文地址:https://www.cnblogs.com/xiaozeng6/p/11105050.html
Copyright © 2020-2023  润新知