将类放在其他类的静态数组中

时间:2015-01-17 22:12:07

标签: python arrays class static

这是一个非常具体的问题,有点难以解释。但这是我的代码的一部分:

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数组中的Fighting发出了错误,因为还没有声明Fighting。然而,飞行中的战斗抵抗是好的,因为战斗已经宣布。

这有一个简单的解决方法吗?我尝试的第一件事就是让这些类看起来像这样:

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

但是当我想要实现这些类时,我必须创建一个令人讨厌的实例。

我已经考虑过声明所有类然后定义所有数组     Normal.resistance = [战斗] 但这似乎有点麻烦。我还想过将它们全部分开并将它们互相导入,但我甚至都不知道这是否有效。如果有人能帮到我,我真的很感激!

- 编辑 -

我最终把它变成了一个带有获取数组函数的枚举,这种方式更有意义

2 个答案:

答案 0 :(得分:0)

这个怎么样:

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):
    ...

答案 1 :(得分:0)

我建议有一个名为species的文件夹(又名,包)('类型'是Python中的保留字,所以我想避免以任何形式使用它),并且species文件夹,每个物种都有一个单独的文件(又名模块)。

通过这种方式,您可以毫无问题地导入任何特定物种的弱点,抗性和免疫特异性物种。

如果您不喜欢species,其他类似于群组的常规字词为kindcategoryvarietybreed和{{ 1}},仅举几例我的头脑。

文件夹示例

classification

文件示例(normal.py)

/species
    __init__.py
    abstract.py (what you call `class Type` I would rename to AbstractSpecies)
    normal.py  (from . import Fighting, Ghost)
    fighting.py  (from . import ...)
    flying.py  (from . import ...)