|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
源代码
import random as r
class Fish:
def __init__(self,x,y):
self.x = r.randint(1,10)
self.y = r.randint(1,10)
def move(self):
x = x-1
print('我的位置是:',self.x,self.y)
class Goldfish(Fish):
pass
class Crap(Fish):
pass
class Salmon(Fish):
pass
class Shark(Fish):
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print('我饿了,就得吃东西!')
self.hungry = False
else:
print('吃饱了,不想再吃了!'):
运行结果:fish =Fish()
Traceback (most recent call last):
File "<pyshell#181>", line 1, in <module>
fish =Fish()
TypeError: __init__() missing 2 required positional arguments: 'x' and 'y'
传入参数之后:>>> fish = Fish(x,y)
Traceback (most recent call last):
File "<pyshell#182>", line 1, in <module>
fish = Fish(x,y)
NameError: name 'x' is not defined
>>> fish = Fish(r.randint(1,10),r.randint(1,10))
>>> fish.move()
Traceback (most recent call last):
File "<pyshell#185>", line 1, in <module>
fish.move()
File "D:/Python34/继承关系3.py", line 9, in move
x = x-1
UnboundLocalError: local variable 'x' referenced before assignment
move函数中把
x = x-1改为self.x = self.x -1
|
|