我正在尝试用Python实现一个简化的术语重写系统(TRS)/符号代数系统。
为此,我真的希望能够在类实例实例化过程中拦截和修改操作数。
我想出的解决方案是创建一个元类来修改类对象(类型为“type”)的典型调用行为。在class Preprocess(type):
"""
Operation argument preprocessing Metaclass.
Classes using this Metaclass must implement the
_preprocess_(*operands, **kwargs)
classmethod.
"""
def __call__(cls, *operands, **kwargs):
pops, pargs = cls._preprocess_(*operands, **kwargs)
return super(Preprocess, cls).__call__(*pops, **pargs)
例如,展开嵌套操作F(F(a,b),c)-->;F(a,b,c)
^{pr2}$
所以,现在这种行为可以通过继承来实现:class Operation(object):
def __init__(self, *operands):
self.operands = operands
class F(Flat, Operation):
pass
这将导致所需的行为:print F(F(1,2,3),4,5).operands
(1,2,3,4,5)
但是,我想合并几