【问题标题】:How to define an operator for a Python class, rather than its instances如何为 Python 类而不是其实例定义运算符
【发布时间】:2019-12-17 13:50:18
【问题描述】:

在 Python 中,我可以为我的类的实例定义“加号”运算符的行为:

class A:
    def __add__(self, x):
        return f"adding {x}"

A() + 3 # returns "adding 3"

但是如何为我的类本身定义一个运算符?通常我会使用 @classmethod 或 @staticmethod 装饰器:

class A:
    @classmethod
    def __add__(cls, x):
        return f"adding {x} to {cls}"

print(A + 1)

但它不起作用:

Traceback (most recent call last):
  File "class_operator.py", line 6, in <module>
    print(A + 1)
TypeError: unsupported operand type(s) for +: 'type' and 'int'

我怎样才能使该代码工作?

【问题讨论】:

    标签: python operator-overloading metaprogramming


    【解决方案1】:

    这里的 Python 参考文档描述了这个问题:https://docs.python.org/3/reference/datamodel.html#special-method-lookup

    您必须使用元类,而不是使用 @classmethod 装饰器:

    class A(type):
        def __add__(cls, x):
            return f"Adding {x} to {cls}"
    
    
    class B(metaclass=A):
        pass
    
    
    print(B + 1) # prints: Adding 1 to <class '__main__.B'>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 2013-11-22
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      相关资源
      最近更新 更多