gpt4 book ai didi

python - 子类没有正确地从父类(super class)继承结构

转载 作者:太空宇宙 更新时间:2023-11-03 14:53:33 25 4
gpt4 key购买 nike

<分区>

我刚开始使用 Python,但我无法弄清楚为什么我会遇到如此简单的类继承问题,尽管我一直在遵循教程的常见用法,但我还没有看到任何人Stack Overflow 上的 else 遇到了这个问题。这是代码(别担心,没什么太复杂的):

import random
import sys
import os

class Animal:
__name = ""
__height = 0
__weight = 0
__sound = 0

def __init__(self, name, height, weight, sound):
self.__name = name
self.__height = height
self.__weight = weight
self.__sound = sound

def toString(self):
return "{} is {} cm tall and {} kilograms and says {}".format(self.__name,
self.__height,
self.__weight,
self.__sound)

cat = Animal ('Whiskers', 33, 10, 'meow')
print(cat.toString())

bird = Animal ('Flutie', 33, 10, 'tweet')
print(bird.toString())

class Dog(Animal):

def __init__(self, name, height, weight, sound):
super(Dog, self).__init__(name, height, weight, sound)

def toString(self):
return "{} is {} cm tall and {} kilograms and says {}".format(self.__name,
self.__height,
self.__weight,
self.__sound)

spot = Dog ('Spot', 53, 27, "Woof")

print(spot.toString())

...这是输出:

Whiskers is 33 cm tall and 10 kilograms and says meow
Flutie is 33 cm tall and 10 kilograms and says tweet
Traceback (most recent call last):
File "C:/.../animal_test.py", line 72, in <module>
print(spot.toString())
File "C:/.../animal_test.py", line 65, in toString
return "{} is {} cm tall and {} kilograms and says {}".format(self.__name,
AttributeError: 'Dog' object has no attribute '_Dog__name'

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com