一次重载多个运算符 [英] python - overloading several operators at once

查看:127
本文介绍了一次重载多个运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义类,我想重载几个关节运算符,想知道是否有一种方法可以避免必须为每个代码单独写出代码.我还找不到任何没有显式地使每个运算符一一重载的示例.

I have a custom class and I want to overload several artihmetic operators, and wonder if there is a way to avoid having to write out the code for each one individually. I haven't been able to find any examples that don't explicity overload each operator one-by-one.

class Foo(object):
    a=0 

    def __init__(self, a):
        self.a=a            

    def __add__(self, other):
        #common logic here
        return Foo(self.a+other.a)

    def __sub__(self, other):
        #common logic here  
        return Foo(self.a-other.a)

    def __mul__(self, other):
        #common logic here
        return Foo(self.a*other.a)

#etc...

逻辑稍微复杂一点,但是常见的模式是每个运算符重载方法都包含一些相同的代码来检查是否允许该操作,然后使用类成员构造一个操作.我想减少冗余代码.这有效:

The logic is slightly more complex than this, but the common pattern is that each operator overload method contains some identical code to check that the operation is allowed, and then constructs an operation using the class members. I want to reduce the redundant code. This works:

class Foo(object):
    a=0 

    def __init__(self, a):
        self.a=a            

    def operate(self, other, operator):
        #common logic here
        a = constructOperation(self.a, other.a, operator)
        return Foo(a)

    def __add__(self, other):
        return self.operate(other, "+")

    def __sub__(self, other):       
        return self.operate(other, "-")     


def constructOperation(operand0, operand1, operator):
    if operator=="+": 
        return operand0 + operand1
    if operator=="-": 
        return operand0 - operand1

但是像这样手动构建操作似乎有点愚蠢.这种方法有意义吗,还是这里有更好的方法?

But it seems kind of silly to be constructing operations manually like that. Does this approach make sense, or is there a better way here?

推荐答案

您可以通过反射和高阶函数来完成此操作,尽管这可能无法很好地继承.

You can do it via reflection and higher order functions, though this may not play well with inheritance.

import operator

def apply_a(func):
    def inner(self, other):
        return Foo(func(self.a, other.a))
    return inner

class Foo(object):
    def __init__(self, a=0):
        self.a = a

for name in ['__add__','__mul__','__sub__']:
    setattr(Foo, name, apply_a(getattr(operator, name)))

这篇关于一次重载多个运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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