Python:在类实例初始化之前修改传递的参数 [英] Python: Modifying passed arguments before class instance initialization

查看:772
本文介绍了Python:在类实例初始化之前修改传递的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python中实现简化的术语重写系统(TRS)/符号代数系统的方法. 为此,我非常希望能够在类实例实例化过程中的特定情况下拦截和修改操作数. 我想到的解决方案是创建一个元类,该元类修改类对象(类型为类型")的典型 call 行为.

I am experimenting with ways to implement a simplified Term Rewriting System (TRS)/Symbolic Algebra System in Python. For this I would really like to be able to be able to intercept and modify the operands in particular cases during the class instance instantiation process. The solution I came up with, was to create a metaclass that modifies the typical call behavior of a class object (of type '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)

An example case would be to expand out nested operations 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 tuple(head), kwargs

因此,现在可以通过继承来实现此行为:

So, now this behavior can be realized through inheritance:

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)

但是,我想组合几个这样的预处理类,并让它们根据自然类mro顺序处理操作数.

However, I would like to combine several such preprocessing classes and have them process the operands sequentially according to the natural class mro.

class Orderless(object):
    """
    Use for commutative Operations to bring into ordered, equivalent 
    form: F(*operands) => F(*sorted(operands))
    """
    __metaclass__ = Preprocess

    @classmethod
    def _preprocess_(cls, *operands, **kwargs):

        return sorted(operands), kwargs

这似乎无法按需工作.定义平面和无序操作类型

And this does not seem to work as wanted. Defining a Flat and Orderless Operation type

class G(Flat, Orderless, Expression):
    pass

仅导致第一个预处理超类为活动".

results in only the first Preprocessing superclass being 'active'.

print G(G(3,2,1),-1,-3).operands
(3,2,1,-1,-3)

如何确保在类实例化之前调用所有预处理类的 preprocess 方法?

How can I ensure that all Preprocessing classes' preprocess methods are called before class instantiation?

更新:

由于我是stackoverflow的新用户,因此我似乎无法正式回答我的问题. 因此,我相信这可能是我能想到的最好的解决方案:

I can't seem to formally answer my question yet due to my status as new stackoverflow user. So, I believe this is probably the best solution I can come up with:

class Preprocess(type):
    """
    Abstract operation argument preprocessing class.
    Subclasses must implement the 
        _preprocess_(*operands, **kwargs)
    classmethod.
    """

    def __call__(cls, *operands, **kwargs):
        for cc in cls.__mro__:
            if hasattr(cc, "_preprocess_"):
                operands, kwargs = cc._preprocess_(*operands, **kwargs)

        return super(Preprocess, cls).__call__(*operands, **kwargs)

我想问题是super(Preprocess, cls).__call__(*operands, **kwargs)不能按预期方式遍历cls的mro.

I guess the problem is that super(Preprocess, cls).__call__(*operands, **kwargs) does not traverse the mro of cls as expected.

推荐答案

我认为您正在以错误的方式进行操作;删除元类,改用类和方法修饰符.

I think you're going about this the wrong way; drop the metaclass, use class and method decorators instead.

例如,将您的公寓定义为:

For example, define your flat as:

@init_args_preprocessor
def flat(operands, kwargs): # No need for asterisks
    head = []
    for o in operands:
        if isinstance(o, cls):
            head += list(o.operands)
        else:
            head.append(o)
    return tuple(head), kwargs

使用init_args_preprocessor装饰器将该函数转换为类装饰器:

With the init_args_preprocessor decorator turning that function into a class decorator:

def init_args_preprocessor(preprocessor):
    def class_decorator(cls):
        orig_init = cls.__init__
        def new_init(self, *args, **kwargs):
            args, kwargs = preprocessor(args, kwargs)
            orig_init(self, *args, **kwargs)
        cls.__init__ = new_init
        return cls
   return class_decorator

现在,代替混合使用装饰器:

And now, instead of mixins use decorators:

class Operation(object):
    def __init__(self, *operands):
        self.operands = operands

@flat
class F(Operation):
    pass

您应该毫无疑问地将类修饰符完美地结合在一起:

And you should have no problem combining the class modifiers cleanly:

@init_args_preprocessor
def orderless(args, kwargs):
    return sorted(args), kwargs

@orderless
@flat
class G(Expression):
   pass

Caveat Emptor:上面的所有代码都未经严格测试.

Caveat Emptor: All code above strictly untested.

这篇关于Python:在类实例初始化之前修改传递的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆