本文共 2549 字,大约阅读时间需要 8 分钟。
class 类名(被继承的类): .....
class Parent: def hello(self): print('正在调用父类的方法T-T')class Child(Parent): passc = Child()c.hello() #正在调用父类的方法T-T# 如果子类中定义和父类同名的方法或者属性,则会自动覆盖父类对应的方法或属性class CChild(Parent): def hello(self): print('老子才不要跟你的姓T_T')d = CChild()d.hello() #老子才不要跟你的姓T_T
import random as fclass Fish: def __init__(self,name): self.name = name self.x = f.randint(0,10) self.y = f.randint(0,10) #假设所有的鱼都是一路向西 def move(self): self.x -=1 print('%s 的位置是:' % self.name,self.x,self.y)class Goldfish(Fish): passclass Carp(Fish): passclass Salmon(Fish): passclass Shark(Fish): def __init__(self,name): self.name = name self.hugry = True def eat(self): if self.hugry: print('老子是 %s,老子怕过谁' % self.name) self.hugry = False else: print('算你小子走运,今天 %s我没胃口' % self.name)fish = Fish('鱼类') fish.move()#鱼类 的位置是: 8 9goldfish = Goldfish('金枪鱼')goldfish.move()#金枪鱼 的位置是: 6 2shark = Shark('大鲨鱼')shark.eat()#老子是 大鲨鱼,老子怕过谁shark.eat()#算你小子走运,今天 大鲨鱼我没胃口# 由于重写了魔法方法__init__,但是新的方法里没有x,y属性# shark.move()报错
class Shark(Fish): def __init__(self,name): self.name = name #此时下面的这个self并不是父类Fish里面的实例对象,而是子类Shark的实例对象 Fish.__init__(self,name) self.hugry = True def eat(self): if self.hugry: print('老子是 %s,老子怕过谁' % self.name) self.hugry = False else: print('算你小子走运,今天 %s我没胃口' % self.name)shark = Shark('大白鲨')shark.move()#大白鲨 的位置是: 7 3
示例 1:
class Shark(Fish): def __init__(self,name): self.name = name# super函数能够帮我们自动找到基类的方法,而且还为我们传入了self参数 super().__init__(name) self.hugry = True def eat(self): if self.hugry: print('老子是 %s,老子怕过谁' % self.name) self.hugry = False else: print('算你小子走运,今天 %s我没胃口' % self.name)
由于不需要给出基类的名字,这就意味着如果需要改变类继承关系,只要改变class语句里的父类即可。
示例 2:
class Bird: def __init__(self): self.hungry = True def eat(self): if self.hungry: print("Aaaah...") self.hungry = False else: print("No,thanks")class SongBird(Bird): def __init__(self): super().__init__() self.sound = "Squawk !" def sing(self): print(self.sound)sb = SongBird()sb.sing()sb.eat()
issubclass
: 转载地址:http://exar.baihongyu.com/