[Python][继承][父类][子类] [多重继承]

#!/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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值