模仿 Python 嵌套或“子”属性的良好数据结构是什么?

问题描述 投票:0回答:1

如何跟踪适用于某些属性但不适用于其他属性的子属性?好像不存在这种事,不过请确认一下。

我在herehere读过一些类似的问题,但一个答案很旧,另一个答案已关闭。

考虑这个例子:

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”。

这是我的课程经验长度,因此我可能会尝试使用字典,但请分享任何可能的解决方案。 TY.

python-3.x class attributes
1个回答
0
投票

要拥有子属性,您可以使用子

class Food:
    def __init__(self, food_groop, food):
        self.food_group = food_groop
        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'

    def get_food(self):
        super().get_food()
        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
© www.soinside.com 2019 - 2024. All rights reserved.