[英]Using a Mixin to Store Configs in a Class (with inheritance)
我有很多默认值是从配置文件加载并存储在结构样式类中的(没有方法,只有变量)。
然后,我有两类,一类定义Molecule
,另一类定义特定种类的分子,这里称为Ligand
,它是从Molecule
继承的。 我希望Ligand
可以访问Molecule
所有方法和变量以及DefaultsMixin
所有变量。 我正在尝试为此使用mixin,但我认为我正在滥用super()
。 这些类的大致概述如下:
class DefaultsMixin:
def __init__(self):
self.memory = 4
self.threads = 2
class Molecule:
def __init__(self, name):
super().__init__(name)
self.name = name
class Ligand(DefaultsMixin, Molecule):
def __init__(self, name):
super().__init__(name)
self.atoms = ['C', 'H']
继承是从右到左,因此Ligand()
的顺序。
我想避免使用合成,因为我想简单地通过名称调用默认值,例如
# What I want to achieve using mixin
mol = Ligand('methane')
mol.threads
>>> 2
# What I want to avoid using composition
# (self.defaults = Defaults() inside Ligand class instead of using mixin)
mol = Ligand('methane')
mol.defaults.threads
>>> 2
如何正确使用super()
来使此mixin工作?
谢谢你的帮助。
您可以调用父对象的init方法
如果查看mixin示例gCoh的链接 ,您会看到需要在mixin中添加* args和** kwargs来传递未使用的参数。 另外(至少对我来说似乎违反直觉),您需要从mixin而不是您的Molecule类中调用super。
这是您想要的行为吗?
class DefaultsMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.memory = 4
self.threads = 2
class Molecule:
def __init__(self, name):
self.name = name
class Ligand(DefaultsMixin, Molecule):
def __init__(self, name):
super().__init__(name)
self.atoms = ['C', 'H']
mol = Ligand('methane')
print(f'The number of threads is {mol.threads}')
print(f'The atoms are {mol.atoms}')
print(f'The name is {mol.name}')
输出:
The number of threads is 2
The atoms are ['C', 'H']
The name is methane
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.