我正在尝试用 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)
Run Code Online (Sandbox Code Playgroud)
一个示例情况是扩展嵌套操作 F(F(a,b),c)-->F(a,b,c)
class Flat(object):
"""
Use for associative Operations to expand nested
expressions of same Head: F(F(x,y),z) => F(x,y,z)
"""
__metaclass__ = Preprocess
@classmethod
def _preprocess_(cls, *operands, **kwargs):
head = []
for o in operands:
if isinstance(o, cls):
head += list(o.operands)
else:
head.append(o)
return …Run Code Online (Sandbox Code Playgroud)