Python 3 生成错误 vs Python 2 使用装饰器

Python 3 generates error vs Python 2 using decorator

使用Python 2.7,以下代码有效:

def AddHex(old_class):
   old_class.__hex__ = lambda self: 'I am a hex!'
   return old_class

@AddHex
class AClass(object):
   """'Empty' class"""
   pass

a = AClass()
print hex(a)

输出:

I am a hex!

使用Python 3.6,出现以下错误:

TypeError: 'AClass' object cannot be interpreted as an integer

如何使此代码 Python 3.6 兼容?

你不能。

在 Python 3 中,hex 寻找 __index__ 函数 returns 一个整数 。您不能使用 hex 打印任意字符串。