使用 Mixin 将配置存储在 Class 中(具有继承性)

Using a Mixin to Store Configs in a Class (with inheritance)

我有很多默认值从配置文件加载并存储在结构样式 class(没有方法,只有变量)。

然后我有两个 class,一个定义 Molecule,另一个定义一种特定的分子,这里称为 Ligand,它继承自 Molecule。我希望 Ligand 能够访问 Molecule 中的所有方法和变量以及 DefaultsMixin 中的所有变量。我正在尝试为此使用 mixin,但我认为我滥用了 super()。 classes 的大致轮廓如下:

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方法

请参阅Calling parent class __init__ with multiple inheritance, what's the right way?

如果您检查 mixin 示例 gCoh's link,您会发现您需要将 *args 和 **kwargs 添加到 mixin 以传递未使用的参数。另外(至少对我来说似乎违反直觉)你需要从 mixin 中调用 super 而不是你的 Molecule class.

这是您想要的行为吗?

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