简体   繁体   中英

sharing attributes between classes in python

I am not sure how to accomplish something that should be straightforward.

I want to define a class. In that class will be subclasses. In those subclasses will be attributes.

Ok, that's easy. But I want the attributes of one subclass to be generated based on the attributes of another of the subclasses. Here is my (wrong) code to try to do that:

class Food(object):
    class Fruits(object):
        crunchy=['Apples', 'Pears']
        juicy=['Limes', 'Lemons']

    class Salads(object):
        import Fruits
        FruitSalad=crunchy+juicy+['Whipped Cream']

Obviously "import Fruits" is wrong here. But how can I accomplish what I need?

-------------edit/addendum--------------------------------------

Ok, so I lose the outer class "Food", that's ok, I never liked it anyway.

I can now instantiate the first class into the second like this:

class Fruits(object):
    crunchy=['Apples', 'Pears']
    juicy=['Limes', 'Lemons']

class Salads(object):
    fruit=Fruits
    FruitSalad=fruit.crunchy+fruit.juicy+['Whipped Cream']

Which is closer, but I really want to lose the "fruit." structure.

Perhaps there is some confusion about subclasses vs. encapsulation . Here is an example hierarchy if you're looking for inheritance. Note that this particular code is not making much use of the hierarchy and just some bare lists would be easier, and the variables are all class variables, not per-instance.

class Food(object):
    pass

class Fruit(Food):
    pass

class Salad(Food):
    pass

class CrunchyFruit(Fruit):
    ingredients = ['apples','pears']

class JuicyFruit(Fruit):
    ingredients = ['limes','lemons']

class FruitSalad(Salad):
    ingredients = JuicyFruit.ingredients + CrunchyFruit.ingredients + ['whipped cream']

print(FruitSalad.ingredients)

Because you are defining this as a nested set of classes, you are needlessly complicating things. The explanation is now going to involve words like "class suite" and why you'd need Fruits.crunchy in one place and Food.Fruits.crunchy in another. You are also trying to concatenate lists and a string, which won't work.

Just keep things simple, create a module named food , then you can do import food and create an instance of food.Salads() .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM