문제

I want my class to return an Integer instance like when you override __str__ But Integer type. I don't understand why the following code wont work.

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 
도움이 되었습니까?

해결책

>>> class A:
    def __new__(cls):
        return 5
>>> A()
5
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top