Python子类错误



我是python的新手,正在为一个学校项目编写这段代码。我收到一些错误消息,但在更正它们时遇到问题。任何指导都将不胜感激。

enter code here
class Mammal():
def __init__(self, name='', size='', sound=''):
self.name = name
self.size = size
self.sound = sound
class Gorilla(Mammal):
def __init__(self, name, size,sound, type):
super().__init__(name, size, sound)
self.type = type

Silverback = Gorilla(Barney, large, grunts)
print("The gorilla type is"+ Gorilla.type)
print(" The gorilla's name is"+ Gorilla.name)
print(' The gorilla is'+ Gorilla.size)
print('the gorilla sound is'+ Gorilla.sound )

class Bear(Mammal):
def __init__(self, name, size,sound, type):
super().__init__(name, size, sound)
self.type = type
Polar = Bear(Henry, large, roar)
print("The bear type is"+ Bear.type)
print(" The bear's name is"+ Bear.name)
print(' The bear is'+ Bear.size)
print('the bear says'+ Bear.sound )

b = Bear()
g = Gorilla()
if (b == g):
print(b.getGenus() + " and " + g.getGenus() + " are of the same genus")
else:
print(b.getGenus() + " and " + g.getGenus() + " are *not* of the same 
genus")

def listenToMammal(Mammal):
print(Mammal.makeNoise())

listenToMammal(B)
listenToMammal(G)

代码只运行到第13行,并给出错误:追踪(最近一次通话(:文件";C:/Users/Owner/PycharmProjects/pythonProject/main.py";,第13行,in银背大猩猩=大猩猩(巴尼,大型,咕哝(名称错误:名称"Barney"未定义

因为它搜索名为Barney的变量,所以没有您定义的变量。对于在初始化对象之前必须用引号传递或定义的参数

silverback = Gorilla("Barney", "large", "grunts")要打印它,不要使用类名,请使用初始化对象的变量。

Print(" the Gorilla type is "+silverback.type)

最新更新