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__
.