首页 > 解决方案 > 继承一个随机类而不覆盖实例化

问题描述

我正在制作事物的层次结构(事物>无机,有机>植物,生物>狗等)以了解类和继承。

我正在尝试实现性,但我目前的解决方案非常老套。它目前只是在生物类中确定,然后功能取决于结果。我希望性成为一个更基本的方面——帮助确定大小、重量和使用哪种方法。为什么男性生物要有怀孕和分娩的方法?这是我目前拥有的(省略了额外的属性以使其更易于阅读):

 class Creature(Organic):

    sex_pool = ('male', 'female')
    weight_range = {'male': (0,0), 'female': (0,0)}

    def __init__(self):
        Creature.population += 1
        super().__init__()
        self._sex = random.choice(self.sex_pool)
        self.weight = self.rand_normal(self.weight_range[self._sex][0],self.weight_range[self._sex][1])
        self._pregnant = False if self._sex is 'female' else None

    @property
    def sex(self):
        return self._sex

    @property
    def pregnant(self):
        return self._pregnant

    @pregnant.setter
    def pregnant(self, boolean):
        if self._sex is 'female':
            if type(boolean) is bool:
                self._pregnant = boolean
            else:
                print("pregnancy attribute must be a boolean value")
        else:
            print("only females have a pregnancy attribute")

相反,我想让 Creatures 继承一个 Sex 类,它随机选择 Male 或 Female 类。我有一个性别类,它在初始化时变为男性或女性,但当然我不能让我的生物类继承它,因为它也会覆盖生物类:

class Male:
    def __init__(self):
        self._sex = 'male'

class Female:
    def __init__(self):
        self._sex = 'female'
        self._pregnant = False

    @property
    def pregnant(self):
        return self._pregnant

    @pregnant.setter
    def pregnant(self, boolean):
        if type(boolean) is bool:
            self._pregnant = boolean
        else:
            print("pregnancy attribute must be a boolean value")
class Sex():
    def __init__(self):
        sex = random.choice((Male, Female))
        self.__class__ = sex

我也试过这个,但它最终使 Sex 类要么总是女性要么总是男性(并且没有正确继承 Organic,但我想这是我应该能够解决的另一件事):

class Sex(random.choice((Male,Female))):
    def __init__(self):
        super().__init__()

class Creature(Sex, Organic):
...

或者,有没有办法在生物 init 上实例化 Sex 类并将属性/方法添加到生物类?但这似乎是一种“伪造”继承的相当老套的方式,即使如此,男性、女性和性别类属性也会丢失(我认为)。

我想我想返回一些继承指令而不是性的类实例,但我不确定这是否真的可能。

我已经筛选了一篇彻底且看似相关的 SO 帖子,但所有示例都覆盖了继承类,这不起作用。python类工厂继承随机父

标签: pythonclassoopinheritancedesign-patterns

解决方案


推荐阅读