Inherited class constructor method

1, call the superclass constructor unbound

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, use the super function

__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()

The case of a class that inherits more of the superclass, only need to use a super function can

Guess you like

Origin www.cnblogs.com/xiaozeng6/p/11105050.html