python - python 2 与 3 中作为类方法的运算符

标签 python

我知道您可以使用元类将运算符重载为类方法:

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/

相关文章:

python - Python 中的堆法则

python - 在 sympy 中切片符号 block 矩阵时保留维度

python - 使用 Django 内联表单集获取 'modelformset_factory without defining ' 字段错误。我究竟做错了什么?

python - 如何在 boto3 中创建源为 sg 的入口规则

python - 为什么要使用 tf.data?

python - xlsxwriter 条件格式 icon_set 中间值 = 0 未显示正确的箭头

python - 无法将 python 输出通过管道传递给程序

python - JSON 使用被调用的值序列化 Django 查询集。我的方法有什么问题吗?

javascript - 文件上传后是否可以留在页面上并收到“确定”消息?

python - 解析 HTML 时遇到问题