4

I defined a class MyInt as a subclass of int, then instantiated an object of it. I found it legal to set a value to a non-existing attribute "x" by assigning .x = 1:

class MyInt(int):
    pass

a = MyInt()
a.x = 1

However if I try to do .x = 1 to an int then it complains

b = 0
b.x = 1


AttributeError: 'int' object has no attribute 'x'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/var/folders/pd/rtb4xpwj0cdd6gk9jr3z3_280000gn/T/ipykernel_66385/2856995082.py in <module>
      1 b = 0
----> 2 b.x = 1

AttributeError: 'int' object has no attribute 'x'

My question is: if MyInt inherits all the methods from int without overriding, why does setattr behave differently on their instances?

edit: by setattr here I meant __setattr__.

Z Che
  • 69
  • 3
  • 2
    I assume you mean `__setattr__`? That method hasn't changed, what's changed is that it now had a `__dict__`, as *all user defined types will be default*, which allows `__setattr__` to handle arbitrary names – juanpa.arrivillaga Aug 21 '21 at 19:51
  • 2
    You can suppress the default `__dict__` by defining `__slots__ = ()` inside the class. – MegaIng Aug 21 '21 at 19:55
  • @juanpa.arrivillaga Interesting, thanks! Indeed, ```a = MyInt(); b = 0; set(dir(a)) - set(dir(b))``` then i got ```{'__dict__', '__module__'}``` – Z Che Aug 21 '21 at 20:06

0 Answers0