#!/usr/bin/env python3
# _*_ coding: utf-8 -*
import random as r
class Fish:
def __init__ (self):
self.x = r.randint(0,100)
self.y = r.randint(0,100)
def move(self):
self.x -= 1
print (self.x, self.y)
class Goldfish(Fish):
pass
class Shark(Fish):
def __init__ (self):
self.hungry = True
def eat(self):
if self.hungry:
print ("吃吃吃")
self.hungry = False
else:
print ("不吃了")
t = Fish()
t.move()
shayu = Shark()
shayu.eat()
shayu.eat()
如果是
>>> shayu = Shark()
>>> shayu.move() # 会报错 子类重写__init__方法会覆盖父类init方法,这里会提示找不到x
# 报错内容
Traceback (most recent call last):
File "123.py", line 32, in <module>
shayu.move()
File "123.py", line 10, in move
self.x -= 1
AttributeError: Shark instance has no attribute 'x'
两种解决方案:
1.调用未绑定的父类 init 下加一个 Fiah.__init__(self)
#!/usr/bin/env python3
# _*_ coding: utf-8 -*
import random as r
class Fish:
def __init__ (self):
self.x = r.randint(0,100)
self.y = r.randint(0,100)
def move(self):
self.x -= 1
print (self.x, self.y)
class Goldfish(Fish):
pass
class Shark(Fish):
def __init__ (self):
Fish.__init__(self)
self.hungry = True
def eat(self):
if self.hungry:
print ("吃吃吃")
self.hungry = False
else:
print ("不吃了")
t = Fish()
t.move()
shayu = Shark()
shayu.eat()
shayu.eat()
shayu.move()
1.super方法 init 下加一个 super().__init__() #self都省了
#!/usr/bin/env python3
# _*_ coding: utf-8 -*
import random as r
class Fish:
def __init__ (self):
self.x = r.randint(0,100)
self.y = r.randint(0,100)
def move(self):
self.x -= 1
print (self.x, self.y)
class Goldfish(Fish):
pass
class Shark(Fish):
def __init__ (self):
super().__init__()
self.hungry = True
def eat(self):
if self.hungry:
print ("吃吃吃")
self.hungry = False
else:
print ("不吃了")
t = Fish()
t.move()
shayu = Shark()
shayu.eat()
shayu.eat()
shayu.move()
多重继承
class 类名(父类1,父类2...父类n)