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

2024-09-30 20:18:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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]

是的,这些是Pokemon类型,它们只是我文件中18个类型中的3个,但它们基本上是相同的。我要做的是让所有这些类都有其他类的静态数组。你知道吗

问题是战争正常。虚弱数组出现错误,因为战斗尚未声明。然而,战争飞行阻力很好,因为已经宣布了战斗。你知道吗

有什么简单的解决办法吗?我尝试的第一件事就是让课程看起来像这样:

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

但是,每当我想实现这些类时,我就必须为它们创建一个实例,这很烦人。你知道吗

我考虑过声明所有的类,然后定义所有的数组,比如 正常电阻=[战斗] 但这似乎有点麻烦。我也想过把它们都分开,然后互相导入,但我甚至不知道这样做是否行得通。如果有人能帮我,我会非常感激的!你知道吗

--编辑--

最后我把它做成了一个枚举,带有获取数组的函数,这样做更有意义


Tags: selftype数组bugclasscolordarkrock
2条回答

我建议使用一个名为species(“type”在Python中是一个保留字,所以我希望避免以任何形式使用它),并且在species文件夹中,每个物种都有一个单独的文件(aka,module)。你知道吗

通过这种方式,你可以导入特定的物种的弱点,抵抗力和免疫力为任何给定的物种没有问题。你知道吗

如果你不喜欢species,其他一般的类词有kindcategoryvarietybreedclassification,这是我脑子里想的几个词。你知道吗

文件夹示例

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

文件示例(正常.py)

from .abstract import AbstractSpecies
from .fighting import Fighting
from .ghost import Ghost


class Normal(AbstractSpecies):
    color      = [168, 168, 120]
    weakness   = [Fighting]
    resistance = []
    immunity   = [Ghost]

这个怎么样:

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

相关问题 更多 >