Python中的抽象类、继承和工厂方法

2024-06-16 08:58:44 发布

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

我对我应该采取的正确方法感到困惑 我正在创造一种游戏,在这个游戏中的主角有配件。你知道吗

所以我在考虑一个名为Item的抽象类。从Item继承的还有抽象类,如眼镜、衬衫等。。。 我认为它应该是抽象的原因是我从来没有创建过眼镜,例如,我创建了一个“绿色阴影”的实例。绿色阴影也是一个类,我认为它应该继承眼镜当然。 我在考虑让Item成为一个抽象类,比如Glasses也成为一个抽象类,但是它们有一个工厂方法来生成眼镜的类型(绿色阴影、蓝色阴影等等)。你知道吗

每件物品都有一个价值属性(基本或稀有)。 我已经开始写一些东西,但是我对实现细节感到困惑。你知道吗

项目:

from enum import Enum
from abc import ABCMeta, abstractmethod

class Worth(Enum):
    BASIC = 0
    RARE = 1

class Item(object):
    __metaclas__ = ABCMeta

    def __init__(self, worth):
        self.worth = worth

    @property
    @abstractmethod
    def type_factory(self,type):
        pass

眼镜和眼镜示例:

from abc import ABCMeta, abstractmethod
import importlib
Enums = importlib.import_module('Enums')
Item = importlib.import_module('Item')

class Glasses(Item):
    __metaclas__ = ABCMeta

    def __init__(self,worth,type):
        super().__init__(worth)
       # self.type = self.type_factory()

    @property
    @abstractmethod
    def type_factory(self,type):
        if type == Enums.GlassesType.BLACK_SHADES:
            return BlackShades()
        # so on..

class BlackShades(Glasses):
    def __init__(self,worth):
        super().__init__(worth)

最好的办法是什么?有没有更好的工厂例子我应该用?也许使用类型类创建会更好?你知道吗

澄清一下:我并不只是想改进这段代码。我不介意使用正确的方法从头开始实现它,因为我缺乏Python方面的经验,所以我不确定这是什么。你知道吗

谢谢


Tags: 方法importselfinitdeftype抽象类item