Python 确保所有模块具有相同参数的模式?
我正在用Python编写以下体系结构的代码。基本上,它是一个模块化合成器,由一组“模块”组成。为了简单起见,现在每个模块都是原子的(没有嵌套的模块) 每个模块包含两个参数,p1和p2。我想确保同一个synth中的每个模块对于p1和p2具有相同的参数值 以下是一种方法,其中有一些样板:Python 确保所有模块具有相同参数的模式?,python,inheritance,design-patterns,Python,Inheritance,Design Patterns,我正在用Python编写以下体系结构的代码。基本上,它是一个模块化合成器,由一组“模块”组成。为了简单起见,现在每个模块都是原子的(没有嵌套的模块) 每个模块包含两个参数,p1和p2。我想确保同一个synth中的每个模块对于p1和p2具有相同的参数值 以下是一种方法,其中有一些样板: DEFAULT_P1 = ... DEFAULT_P2 = ... class Module: """ Abstract base class. "
DEFAULT_P1 = ...
DEFAULT_P2 = ...
class Module:
"""
Abstract base class.
"""
def __init__(
self, p1: int = DEFAULT_P1, p2: int = DEFAULT_P2
):
self.p1 = p1
self.p2 = p2
class ModuleK(Module):
"""
A handful of submodules.
"""
def __init__(
self,
... other params
p1: int = DEFAULT_P1,
p2: int = DEFAULT_P2,
):
super().__init__(p1=p1, p2=p2)
...
class Synth:
"""
An abstract class for a modular synth, ensuring that all modules
have the same sample and control rate.
"""
def __init__(self, modules: Tuple[Module]):
# Check that we are not mixing different control rates or sample rates
for m in modules[:1]:
assert m.p1 == modules[0].p1
assert m.p1 == modules[0].p2
下面是一个使用globals的更简洁的方法。我担心这可能会产生副作用,即不能在同一运行时使用不同的p1和p2使用两个Synth,除非您做一些非常精细和脆弱的事情
DEFAULT_P1 = ...
DEFAULT_P2 = ...
class Module:
"""
Abstract base class.
"""
def __init__(
self
):
self.p1 = DEFAULT_P1
self.p2 = DEFAULT_P2
class ModuleK(Module):
"""
A handful of submodules.
"""
def __init__(
self,
... other params
):
...
我还考虑了从封装p1和p2的类继承。但是,您仍然必须检查同一synth中的所有模块是否继承自同一种封装类。因为它只有两个参数,所以在任何方面都不会使事情更符合人体工程学
是否有我遗漏的模式?此处的“模块工厂”可能会有所帮助。首先,背景:
DEFAULT_P1 = 1
DEFAULT_P2 = 2
class Module:
def __init__(self, p1: int = DEFAULT_P1, p2: int = DEFAULT_P2, **other_args):
self.p1: int = p1
self.p2: int = p2
class ModuleX(Module): # May take other arguments other than p1 and p2
pass
class ModuleY(Module):
pass
然后:
然后,要使用它:
f = ModuleFactory(1, 2)
x_inst = f.create_module_instance(ModuleX, some_x_thing=1)
y_inst = f.create_module_instance(ModuleY, some_y_thing=2)
p1
和p2
值只提供给工厂一次,然后在创建模块实例时自动提供。模块可能依赖于某种类型的SynthContext
类提供的这些值,而不是每个模块都有自己的采样率和控制率?似乎永远不会有一个模块不连接到synth.FWIW的情况,我认为您的第一种方法很好。也就是说,我认为您应该使用来检查模块[1:::::
中的m。
f = ModuleFactory(1, 2)
x_inst = f.create_module_instance(ModuleX, some_x_thing=1)
y_inst = f.create_module_instance(ModuleY, some_y_thing=2)