
继承学习笔记
继承
子类重写了父类的方法,
1.调用未绑定过的父类方法
2.使用super函数
e.g.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
import random as r
class Fish: def __init__(self): self.x = r.randint(0,10) self.y = r.randint(0,10)
def move(self): self.x -= 1 print("My position is :",self.x,self.y)
class Goldfish(Fish): pass
class Salmon(Fish): """docstring for Salmon""" #def __init__() def __init__(self): super().__init__() self.hungry = True def eat(self): if self.hungry: print("Salmon is full") self.hungry = False else: print("salmon eats too much") # class Salmon(Fish): # """docstring for Salmon""" # #def __init__() # def __init__(self): # super(Salmon,self).__init__() # self.hungry = True # def eat(self): # if self.hungry: # print("Salmon is full") # self.hungry = False # else: # print("salmon eats too much")
class Shark(Fish):
def __init__(self): Fish.__init__(self) #self是子类的对象Fish.__init__(Shark) self.hungry = True def eat(self): if self.hungry: print("shark is full") self.hungry = False else: print("shark eats too much")
salmon = Salmon() salmon.move() salmon.eat()
shark = Shark() shark.move() shark.eat()
|
python严格要求方法需要有实例才可被调用,及绑定
缺少了self参数(对象):
1 2 3 4 5 6 7 8 9 10 11
|
>>> class BB: ... def printBB(): ... print('not binded') ... >>> BB.printBB() not binded >>> bb = BB() >>> bb.printBB() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: printBB() takes 0 positional arguments but 1 was given
|
1 2 3 4 5 6 7
|
>>> class BB: ... def printBB(self): ... print('binded') ... >>> bb = BB() >>> bb.printBB() binded
|
近期评论