在类级别属性中存储(自我)的实例列表



我有一个类,我想在其中存储同一类对象的静态参考列表。例如:

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

这会导致NameError: name 'Apple' is not defined错误。为什么这不起作用?

我将代码更改为以下内容,该代码似乎在控制台上工作:

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')]

有更好的方法吗?这个模块内部和外部是否可以工作,这是否取决于我导入模块的方式?

使用classMethod将苹果附加到类列表中。

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')

NICE_APPLES声明为Apple类中的空列表,然后在__init__()中,完成所有本地变量后,将self附加到列表中。

class Apple(object):
    NICE_APPLES = []
    def __init__(self, name, color, keep=False):
        self.name = name
        self.color = color
        if keep:
            Apple.NICE_APPLES.append(self)

您可以从类方法中创建新的类实例,我认为这是一种干净的方法,而且如果您想存储最新创建的OBJ,除了列表硬子:

class Apple:
    NICE_APPLES = []
    def __init__(self, name, colour):
        self.name = name
        self.colour = colour
    @classmethod
    def init_with_nice_apples(self, name, colour):
        Apple.NICE_APPLES = [Apple('Elstar', 'Green'), Apple('Braeburn', 'Red')] #hardcore list
        self.__init__(self,name, colour)
        Apple.NICE_APPLES.append(self)
        return self
ap = Apple.init_with_nice_apples("Delicius", "Red")

最新更新