【问题标题】:How do you overload the caret (^) operator in python你如何在python中重载插入符号(^)运算符
【发布时间】:2012-05-15 23:56:56
【问题描述】:

我需要覆盖类中的插入符号行为,但我不确定哪个运算符重载适用于它。例如:

class A: 
    def __init__(self, f):
        self.f = f
    def __caret__(self, other):
        return self.f^other.f

print A(1)^A(2)

此代码错误:

TypeError: unsupported operand type(s) for ^: 'instance' and 'instance'

如何构造类以便控制行为?

【问题讨论】:

  • 我看到您使用的是 Python 2。您应该始终使用 class A(object): 而不是 class A:。永远不要使用旧式类。
  • 这是为什么呢?不从对象继承有什么坏处?

标签: python operator-overloading caret


【解决方案1】:

定义A.__xor__()A.__rxor__()

【讨论】:

    【解决方案2】:

    ^ 是一个异或运算符。您可以使用__xor__ 方法重载它。

    例如

    >>> class One:
    ...     def __xor__(self, other):
    ...             return 1 ^ other
    ... 
    >>> o = One()
    >>> o ^ 1
    0
    >>> o ^ 0
    1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 2010-12-15
      • 2012-08-10
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多