如何跟踪适用于某些属性但不适用于其他属性的子属性?好像不存在这种事,不过请确认一下。
我在here和here读过一些类似的问题,但一个答案很旧,另一个答案已关闭。
考虑这个例子:
class FoodTest:
def __init__(self, food_group, food, variety=''):
self.food_group = food_group
self.food = food
self.variety = variety
def get_food(self):
print(f'I like {self.food}s, which are a {self.food_group}')
if self.food == 'apple':
print(f'The {self.food} variety is {self.variety}')
oran = FoodTest('fruit', 'orange')
oran.get_food()
app = FoodTest('fruit', 'apple', 'fuji')
app.get_food()
输出:
I like oranges, which are a fruit
I like apples, which are a fruit
The apple variety is fuji
我想要的是仅适用于苹果的品种(富士、青苹果等),而不是橙子。当然,我可以访问 app.variety,但我真正寻找的是“app.food.variety”。
要拥有子属性,您可以使用子类。 每个
Food
都知道它的属性。
class Food:
def __init__(self, food_group, food):
self.food_group = food_group
self.food = food
def get_food(self):
print(f'I like {self.food}s, which are a {self.food_group}')
class Apple(Food):
def __init__(self):
super().__init__('fruit', 'apple')
self.variety = 'fuji' # extra attribute for apple
def get_food(self):
super().get_food()
# Extra sentence for variety
print(f'The {self.food} variety is {self.variety}')
class Orange(Food):
def __init__(self):
super().__init__('fruit', 'orange')
oran = Orange()
oran.get_food()
app = Apple()
app.get_food()
输出:
I like oranges, which are a fruit
I like apples, which are a fruit
The apple variety is fuji