【发布时间】:2022-07-22 01:33:04
【问题描述】:
为什么 cat1.set_size() 函数返回 None 而不是 "small" 和 cat2.color 函数返回 "<__ main __. tiger object at>" 而不是 "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)
结论:
black indoor None
<__main__.Tiger object at 0x000002711C6D4DF0> wild big
【问题讨论】:
-
(1) 因为你没有返回任何东西。如果您希望它返回新大小,请添加
return self.size。 (2) 因为需要将self传递给super().__init__函数。 -
set_size没有理由争论,因为你从不看争论。Tiger.set_size也没有任何理由打电话给super().set_size。 -
cat1_size!=cat1.size -
super().__init__(color, cat_type)必须是super().__init__(self, color, cat_type) -
该函数不包含任何
return语句。你为什么期望它返回任何东西?