gpt4 book ai didi

python - 对象没有从父类(super class)继承函数?

转载 作者:行者123 更新时间:2023-11-30 22:44:47 27 4
gpt4 key购买 nike

所以我不断得到

error: " AttributeError: 'Dog' object has no attribute '_Dog__name'"

事情是print(spot.get_name())工作正常。另外,当我尝试 spot.multiple_sounds() 时,也同样失败了。我认为问题是当我尝试在对象定义的函数中从父类(super class)调用对象属性时。我不明白为什么。我是根据教程完成所有这些的,并且代码与他的相同。我认为这可能是因为他使用的是 python2.x,而我使用的是spyder python3.x,但我不知道。非常感谢任何帮助。

import random
import os
import sys

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 set_name(self, name):
self.__name = name

def get_name(self):
return(self.__name)

def set_height(self, height):
self.__height = height

def get_height(self):
return(self.__height)

def set_weight(self, weight):
self.__weight = weight

def get_weight(self):
return(self.__weight)

def set_sound(self, sound):
self.__sound = sound

def get_sound(self):
return(self.__sound)

def get_type(self):
print("animal")

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())

class Dog(Animal):

__owner = ""

def __init__(self, name, height, weight, sound, owner):
self.__owner = owner
super().__init__(name, height, weight, sound)

def set_owner(self,owner):
self.__owner = owner

def get_owner(self):
return self.__owner

def get_type(self):
print("Dog")

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

def multiple_sounds(self, how_many=None):
if how_many is None:
print(self.getsound())
else:
print(self.getsound()*how_many)

spot = Dog("Spot", 53, 27, "Ruff", "Some Guy")
print(spot.get_name())
print(spot.toString())

最佳答案

在Python中,__fieldName模拟私有(private)字段,表示字段名中的两个下划线。因此,此类字段无法从派生类访问,但您仍然可以使用 getter 获取它们。

关于python - 对象没有从父类(super class)继承函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41405959/

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