I'm new to python and just trying to test the syntax and get to know it. The code below works fine except for when I get to inheritance. The final command "toString" function is not working and I can't for the life of me figure out why.
I'm sure I'm not doing something the most efficient way, but even if there's a more efficient way I'd first like to understand why what I'm doing is wrong. thanks a lot. Please let me know if I need to clarify anything
#!/bin/python
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.__heiight
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 {} inches tall, {} lbs, and says {}".format(self.__name, self.__height,self.__weight,self.__sound))
objCat = Animal('Whiskers', 33, 10, 'Meow')
print (objCat.toString())
# Attempt Inheritance
class cDog(Animal):
__owner=""
def __init__(self,name,height,weight,sound,owner):
self.__owner=owner
Animal.__init__(self,name,height,weight,sound)
def __str__(self):
return ("{}".format(self.__height))
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 {} inches tall, {} lbs, says {}, and is owned by, {}".format(self.__name,self.__height,self.__weight,self.__sound,self.__owner))
objDog = cDog('Brewsky', 20, 75, 'Ruff', 'Jared')
print (objDog.toString())
In your Animal
class, the double underscore before the name of the attributes has made them (sort of) private.
Just delete the double underscore (or change it to one underscore, if you want to keep a weak indicator) and it will be fixed. See this question for more information.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.