python - 继承一个随机类而不覆盖实例化
问题描述
我正在制作事物的层次结构(事物>无机,有机>植物,生物>狗等)以了解类和继承。
我正在尝试实现性,但我目前的解决方案非常老套。它目前只是在生物类中确定,然后功能取决于结果。我希望性成为一个更基本的方面——帮助确定大小、重量和使用哪种方法。为什么男性生物要有怀孕和分娩的方法?这是我目前拥有的(省略了额外的属性以使其更易于阅读):
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类工厂继承随机父
解决方案
推荐阅读
- python - 无法将 Py 文件作为批处理 .BAT 文件运行
- flutter - 如何在颤振中使用 NFC 在两部手机之间发送数据?
- javascript - 无法使用授权代码流向 Web Playback API 进行身份验证
- ruby-on-rails - 如何让路由助手使用现有参数?
- react-native - npm start 命令在本机反应中给出错误
- google-apps-script - 谷歌应用脚本没有遍历所有文件
- java - 如何在自定义对象中循环遍历 ArrayList?
- python - 根据 txt 文件加载复选框值
- reactjs - 使用 React Hooks 处理连续相同的 useFetch 调用的最佳实践?
- javascript - Jquery 在一个函数内部工作,但只针对其中一个调用,另一个我必须在 Chrome 控制台中手动执行