Why does the cat1.set_size() function return None instead of "small" and the cat2.color function returns "<__ main __. Tiger object at 0x000002711C6D4DF0>" instead of "white"?
class Cat:
def __init__(self, color, cat_type):
self.size = "undefined"
self.color = color
self.cat_type = cat_type
def set_size(self, cat_type):
if self.cat_type == "indoor":
self.size = "small"
else:
pass
class Tiger(Cat):
def __init__(self, color, cat_type):
super().__init__(color, cat_type)
def set_size(self, cat_type):
super().__init__(self, cat_type)
if self.cat_type == "wild":
self.size = "big"
else:
self.size = "undefined"
cat1 = Cat(color="black", cat_type="indoor")
cat1_size = cat1.set_size("indoor")
print(cat1.color, cat1.cat_type, cat1_size)
cat2 = Tiger(color="white", cat_type="wild")
cat2.set_size("wild")
print(cat2.color, cat2.cat_type, cat2.size)
Conclusion:
black indoor None
<__main__.Tiger object at 0x000002711C6D4DF0> wild big
>Solution :
Here’s a better organization.
class Cat:
def __init__(self, color, cat_type):
self.size = "undefined"
self.color = color
self.cat_type = cat_type
def set_size(self):
if self.cat_type == "indoor":
self.size = "small"
class Tiger(Cat):
def set_size(self):
if self.cat_type == "wild":
self.size = "big"
cat1 = Cat(color="black", cat_type="indoor")
cat1.set_size()
print(cat1.color, cat1.cat_type, cat1.size)
cat2 = Tiger(color="white", cat_type="wild")
cat2.set_size()
print(cat2.color, cat2.cat_type, cat2.size)
This still has problems, though. The size of the cat should not be determined by "wild" or "indoor". A Tiger, as a specific kind of Cat, should always have its size set to "big". You might have another subclass called Domestic that has its size set to "small".