我知道您可以使用元类将运算符重载为类方法:
class _Two(type):
def __add__(self, other):
return (2 + other)
class Two(object):
__metaclass__ = _Two
Two + 3 # 5
它在 Python 2.7.6 中工作,但在 3.4.0 中失败并出现以下错误:
TypeError: unsupported operand type(s) for +: 'type' and 'int'
这是为什么?
您可以通过与这两个版本兼容的方式来完成此操作,如下所示:
class _Two(type):
def __add__(self, other):
return (2 + other)
class Two(_Two('', (object,), {})): pass
Two + 3 # 5
我明白为什么第二个版本有效,但在我看来,它的功能与第一个版本基本相同,那么我错过了什么?
最佳答案
Python3中使用元类的正确方法是:
class Two(metaclass=_Two):
...
也就是说,添加 __metaclass__
没有什么特别的。作为Python3中的类属性。您将得到与您所看到的相同的错误:
>>> class Two(object):
this_does_nothing_special = _Two
>>> Two + 3
TypeError: unsupported operand type(s) for +: 'type' and 'int'
关于python - python 2 与 3 中作为类方法的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28074041/