这是一个非常具体的问题,很难解释。但这是我的一部分准则:

class Type:
    color      = [168, 168, 120]
    weakness   = []
    resistance = []
    immunity   = []

#**************************************************************************
#Defines all types---------------------------------------------------------
#**************************************************************************
class Normal(Type):
    color      = [168, 168, 120]
    weakness   = [Fighting]
    resistance = []
    immunity   = [Ghost]

class Fighting(Type):
    color      = [192, 48, 40]
    weakness   = [Flying, Psychic, Fairy]
    resistance = [Rock, Bug, Dark]
    immunity   = []

class Flying(Type):
    color      = [168, 144, 240]
    weakness   = [Rock, Electric, Ice]
    resistance = [Fighting, Bug, Grass]
    immunity   = [Ground]

是的,这是口袋妖怪的类型,在我的文件中,这只是18种类型中的3种,但它们基本上都是一样的。我要做的是让所有这些类都有其他类的静态数组。
问题是,Normal.weakness数组中的战斗给出了一个错误,因为战斗尚未声明。然而,在飞行中的战斗。抵抗是好的,因为战斗已经宣布。
有什么简单的解决办法吗?我首先尝试的是让课程看起来像这样:
class Fighting(Type):
    def __init__(self):
        self.color      = [192, 48, 40]
        self.weakness   = [Flying, Psychic, Fairy]
        self.resistance = [Rock, Bug, Dark]
        self.immunity   = []

但是,每当我想实现这些类时,我就必须为它们创建一个实例,这很烦人。
我考虑过声明所有的类,然后定义所有的数组,比如
正常。抵抗力=[战斗]
但这似乎有点麻烦。我也想过把它们分开,然后互相导入,但我甚至不知道这样是否可行。如果有人能帮我,我将非常感谢!
--编辑--
最后我把它变成了一个枚举,它包含了获取数组的函数,这样做更有意义

最佳答案

这个怎么样:

class Type:
    @classmethod
    def classInit(cls):
            if not hasattr(cls, color):
                cls.color = [168, 168, 120]
                cls.weakness = []
                cls.resistance = []
                cls.immunity   = []
    def __init__(self):
        self.classInit()  #only does something the first time it is called
class Normal(Type):
    ...
class Flying(Type):
    ...

10-06 05:18
查看更多