Consider this code:
class testobj( object ): ...
x = testobj()
x.toast = 'toast'
print( x.toast ) # <-- toast
y = object()
y.toast = 'toast'
The last line produces the error
AttributeError Traceback (most recent call last)
<ipython-input-24-873470c47cb3> in <module>()
----> 1 y.toast = 'toast'
AttributeError: 'object' object has no attribute 'toast'
I also tried
class testobj2( object ):
def __init__( self ):
super().__init__()
which behaves the same way, allowing arbitrary attributes to be set.
Based on my understanding of inheritance in Python, I would expect testobj
to have all the same behavior (all same methods, including __setattr__
) as object
, since it's a subclass and no new methods have been defined. However, it is not the same because the above code allows me to set an arbitrary attribute. Why does this happen and how can I disallow setting of arbitrary attributes?