【问题标题】:Defining arithmetic operations on python classes在 python 类上定义算术运算
【发布时间】:2019-07-21 20:13:02
【问题描述】:

我试图弄清楚是否可以在 python 类上定义算术运算。我想做的事情是:

class a():
    @classmethod
    def __add__(cls, other):
        pass

a + a

但是,我当然明白:

TypeError: unsupported operand type(s) for +: 'type' and 'type'

这样的事情有可能吗?

【问题讨论】:

  • 你能举个例子吗?

标签: python python-3.x


【解决方案1】:

a + a 将被解释为type(a).__add__(a, a),这意味着您必须在元类型级别定义方法。例如,一个(不一定正确)实现创建了一个继承自两个操作数的新类:

class Addable(type):
    def __add__(cls, other):
        class child(cls, other, metaclass=Addable):
            pass
        return child

class A(metaclass=Addable):
    pass

class B(metaclass=Addable):
    pass

然后

>>> A + B
<class '__main__.Addable.__add__.<locals>.child'>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-11
    • 2013-02-15
    • 2018-01-09
    • 1970-01-01
    • 2020-07-13
    • 2014-08-31
    • 2011-01-24
    • 1970-01-01
    相关资源
    最近更新 更多