如何使类返回整数实例

Con*_*vid 1 python class instance python-3.x

我希望我的类返回一个 Integer 实例,就像您覆盖__str__But Integer 类型时一样。我不明白为什么下面的代码不起作用。

class A:
    def __init__(self):
        global x
        x=5
    def __new__(cls):
        return  x       
print(A())
#it says: NameError: global name 'x' is not defined 
Run Code Online (Sandbox Code Playgroud)

pba*_*rio 5

>>> class A:
    def __new__(cls):
        return 5
>>> A()
5
Run Code Online (Sandbox Code Playgroud)