魔法

构造函数:初始化方法,命名为__init__,在对象创建后自动调用。、

class Foo:
    def __init__(self):
        self.somevar = 42

f = Foo()
print(f.somevar)

 重写普通方法:未重写之前

class A:
    def hello(self):
        print('i am A')

class B(A):
    pass

a = A()
b = B()
print(a.hello())
print(b.hello())

i am A

i am A

调用超类的构造函数:

class Bird:
    def __init__(self):
        self.hungry = True
    def eat(self):
        if self.hungry:
            print('hahahaha')
            self.hungry = False
        else:
            print('NO,thanks')
b = Bird()
print(b.eat())
print(b.eat())
#增加一个功能,此时调用eat()时会报错,SongBird重写了构造函数但没有初始化hungry代码
class SongBird(Bird):
def __init__(self):
self.sound = 'gagaga'
def sing(self):
print(self.sound)

sb = SongBird()
print(sb.sing())
print(sb.eat())

解决方法:调用超类的构造函数,或者使用super

class SongBird:
    def __init__(self):
        Bird.__init__()
        self.sound = 'gagagaga'
    def sing(self):
        print(self.sound)
        
#使用超类
class
SongBird(Bird): def __init__(self): super().__init__() self.sound = 'gagagaga' def sing(self): print(self.sound)
原文地址:https://www.cnblogs.com/wang-jie-devops/p/10856646.html