f = FooBar('aaa')print(f.somevar)k = FooBar('xuyoujia')print(k.somevar,k.key)z = FooBar('xuyoujia')print(z.somevar,z.key)
class A:def hello(self):print('hello,I'm A')
class B(A):def hello(self):print('hello,I'm B')
a = A()b = B()a.hello()b.hello()
#如果继承的类没有实现超类的构造方法,有可能出现AttributError错误class Bird:def init(self):self.hungry = Truedef eat(self):if self.hungry:print('Aaaah...')self.hungry = Falseelse:print('No , thanks!')
b = Bird()
b.eat()
b.eat()
class SingBird(Bird):def init(self):#Bird.init(self) #1、调用未绑定的超类构造方法super(SingBird,self).init() #2、使用super函数self.sing1 = 'quawk'def sing(self):print(self.sing1)
sb = SingBird()#注:'SingBird' object has no attribute 'hungry' SingBird 未重写__init__方法,未初始化hungrysb.eat()
sb.sing()
sb.eat()sb.eat()
评论