2017-03-03 24 views
-1

使用Python 2.7,下面的代碼工作:Python 3中產生誤差VS Python 2中使用裝飾

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?

+0

你能給出完整的堆棧跟蹤錯誤嗎? – Nilesh

+1

Python 3沒有'__hex__'方法。完全一樣。這不是裝飾問題;你可以在沒有裝飾器的情況下進行測試;-) –

回答

2

你不能。

在Python 3中,hex尋找__index__函數,返回整數。您不能使用hex來打印任意字符串。