class animal(object):
def __init__(self,name):
self.name = name
def eat(self,food):
print("{} is eating".format(self.name,food))
class dog():
def fetch(self,thing):
print("{} get the {}".format(self.name,thing))
s = dog('r')
错误:回溯(最近一次调用最后一次):文件“C:\ EclipseWorkspaces \ csse120 \ LearnPython \ _ inheritance.py”,第14行,s = dog('r')TypeError:dog()不带参数
Cant figure out whats wrong, please help.
由于您的错误表明您正在尝试通过将'r'参数传递给Dog类构造函数来创建Dog类的对象。但Dog类没有构造函数,它接受char或字符串文字作为参数。看起来你正在尝试使用Animal类构造函数来创建Dog对象(Dogs是Animal类的子类)
class animal(object):
def __init__(self,name):
self.name = name
要解决此错误,您应首先继承Dog类,然后创建Dog对象。要子类化Animal类,
class dog(animal):
def fetch(self,thing):
print("{} get the {}".format(self.name,thing))
现在,您可以使用Animal类构造函数并使用s = dog('r')
语句创建Dog对象。
提示: - 我认为从PEP8样式约定中描述的类名开头使用CapWords约定是好的。
你错过了那只狗继承了动物的形象
class Animal(object):
def __init__(self,name):
self.name = name
def eat(self,food):
print("{} is eating".format(self.name,food))
class Dog(Animal):
def fetch(self,thing):
print("{} get the {}".format(self.name,thing))
s = Dog('r')