1

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 
4
  • this code is working for me..prints <__main__.A instance at 0x01E4A800> Commented May 8, 2014 at 7:53
  • I am using python 3.3 and i just checked it again. won't work. Commented May 8, 2014 at 7:54
  • 4
    @ConfuzzeledDavid It's because __new__ is called before __init__. Plus whatever you are trying to do is pure evil. What's the point in overriding __new__ like you do? Just use a function. Commented May 8, 2014 at 7:59
  • You mention __str__ so are you after the same for __int__? Or - are you trying to subclass/otherwise implement your own int like object? Commented May 8, 2014 at 8:06

1 Answer 1

5
>>> class A:
    def __new__(cls):
        return 5
>>> A()
5
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That's exactly what i wanted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.