Confuzzeled David
Confuzzeled David

Reputation: 383

how to make a class return integer instance

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 

Upvotes: 1

Views: 3992

Answers (1)

pbacterio
pbacterio

Reputation: 1152

>>> class A:
    def __new__(cls):
        return 5
>>> A()
5

Upvotes: 5

Related Questions