面向对象:继承(运行程序self出错)什么原因
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("我现在的位置是",self.x,self.y)
class GoldFish(Fish):
pass
class Carp(Fish):
pass
class Salmon(Fish):
pass
class Shark(self):
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry :
print("现在我还没吃饱")
self.hungry =False
else:
print("吃的太饱了")
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:/Users/Administrator/AppData/Local/Programs/Python/Python37/p11-2.py
Traceback (most recent call last):
File "C:/Users/Administrator/AppData/Local/Programs/Python/Python37/p11-2.py", line 22, in <module>
class Shark(self):
NameError: name 'self' is not defined
>>> class Shark(self): 这个类不是继承 self,而是继承Fish 类!!! 荀命不保 发表于 2020-8-30 20:41
class Shark(self): 这个类不是继承 self,而是继承Fish 类!!!
那不应该是这样:
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("我现在的位置是",self.x,self.y)
class GoldFish(Fish):
pass
class Carp(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("吃的太饱了") 呵呵呵呵呵呵呵呵呵呵。。。
你理解错类后面括号的意思了。。
括号用来给Python说:“我要创建一个叫‘shark’的类,他可以用Fish类的方法和属性”
但你要继承self类,Python找遍了内置对象父类和你创建的类,没有找到self类,Python懵了,你要我继承神马呀???
于是就报错了。 括号里面的是要继承的父类的名称,你给了个self,Python找得到self这个类吗?
改成class Shark(Fish):
页:
[1]