<p>在创建类之后很容易将方法添加到类中,它们只是类属性。这里最困难的部分是,您需要动态创建新函数,从原始类克隆方法,以便能够更改其签名</p>
<p>它不是Python最清晰的部分,官方参考文档中没有记录动态函数创建,但可以在SO上找到:<a href="https://stackoverflow.com/q/11291242/3545273">Python: dynamically create function at runtime</a></p>
<p>所以这里有一个可能的方法:</p>
<pre><code># have the new class derive from the common base
class TimeFormula(VecFormula):
"same as FreqFormula, but the omega parameter is renamed to t"
pass
# loop over methods of origina class
for i,j in inspect.getmembers(FreqFormula, inspect.isfunction):
# copy the __init__ special method
if i == '__init__':
setattr(TimeFormula, i, j)
elif i.startswith('__'): continue # ignore all other special attributes
if not j.__qualname__.endswith('.'.join((FreqFormula.__name__, i))):
continue # ignore methods defined in parent classes
# clone the method from the original class
spec = inspect.getfullargspec(j)
newspec = inspect.FullArgSpec(['t' if i == 'omega' else i
for i in spec.args], *spec[1:])
f = types.FunctionType(j.__code__, j.__globals__, i, newspec, j.__closure__)
f.__qualname__ = '.'.join((TimeFormula.__qualname__, i))
# adjust the signature
sig = inspect.signature(j)
if ('omega' in sig.parameters):
f.__signature__ = sig.replace(
parameters = [p.replace(name='t') if name == 'omega' else p
for name, p in sig.parameters.items()])
# and finally insert the new method in the class
setattr(TimeFormula, i, f)
</code></pre>