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 
Bach
  • 6,145
  • 7
  • 36
  • 61
Confuzzeled David
  • 363
  • 1
  • 5
  • 10
  • this code is working for me..prints <__main__.A instance at 0x01E4A800> – sundar nataraj May 08 '14 at 07:53
  • I am using python 3.3 and i just checked it again. won't work. – Confuzzeled David May 08 '14 at 07: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. – freakish May 08 '14 at 07:59
  • You mention `__str__` so are you after the same for [`__int__`](http://stackoverflow.com/questions/11575393/overload-int-in-python)? Or - are you trying to subclass/otherwise implement your own `int` like object? – Jon Clements May 08 '14 at 08:06

1 Answers1

5
>>> class A:
    def __new__(cls):
        return 5
>>> A()
5
pbacterio
  • 1,094
  • 6
  • 12