Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing list of instances (of self) in class level attribute?

I have a class in which I would like to store a static reference list of objects of the same class. For example:

class Apple:

    NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'), 
        Apple('Pink Lady', 'Pink')]

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

This results in a NameError: name 'Apple' is not defined error. Why doesn't this work?

I've changed the code to the following, which seems to work on the console:

class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

Apple.NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red'), 
        Apple('Pink Lady', 'Pink')]

Is there a better way to do this? Will this work inside and outside the module, and is this dependent on the way I import the module?

like image 692
Pepijn Avatar asked Feb 01 '26 21:02

Pepijn


1 Answers

use a classmethod to append apples to your class list.

class Apple:

    NICE_APPLES = []

    def __init__(self, name, colour):
        self.name = name
        self.colour = colour

    @classmethod
    def add_nice_apple(cls, name, colour):
        cls.NICE_APPLES.append(cls(name, colour))


Apple.add_nice_apple('Elstar','Green')
Apple.add_nice_apple('Braeburn','Red')
like image 177
olisch Avatar answered Feb 03 '26 11:02

olisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!