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?
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With