微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python子类错误

如何解决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,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,sound)
    self.type = type

Polar = Bear(Henry,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:/用户/所有者/PycharmProjects/pythonProject/main.py”,第13行 银背=大猩猩(Barney,大,咕unt声) NameError:名称“ Barney”未定义

解决方法

因为它搜索名为Barney的变量,所以您没有定义任何变量。 对于参数,您必须先加上引号或在插入对象之前进行定义

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。