This thing just came in my mind when i am doing some stuff related to oop. If i have a class like this:
>>> class foo(object):
def __init__(self):
pass
Now we can set any random attribute for a foo
instance like this:
>>> a=foo()
>>> a.any_attribute="any-value"
But why cannot we do this for other python structural objects such as list or dict objects:
>>> l=[1,2,3,4]
>>> l.some_attribute="any-value"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'some_attribute'
I am trying to understand the logic and perspective behind this. My explanation is like this:-
Since all python objects have a __setattr__
methods which is inherited from the Object
base class.While we set an attribute of a python object using the syntax: a.any_attribute="any-value"
,the __setattr__
method is called. Since,my foo()
, an instance of foo
class has no restriction of setting only pre-defined attributes, it gives the freedom of setting any attribute.
But in the case of lists and other data structural objects, there must be some overidden behaviour for the __setattr__
method which only allows setting of predefined attributes.
Am i right? If i am right,so what is the basic semantics behind this. Why we are not allowed setting any random attriubutes for these type of objects. Are there any drawbacks or any violation of basic python beliefs, if this behaviour is allowed ?
I know that i might be wrong at certain points but since the question sounds interesting to me, I asked. Regards.
EDIT - OK, i understood the answer,the fact that the class should have a __dict__
method for adding any random attribute to its instance.But, the main question is that
Are there any drawbacks or any violation of basic python beliefs, if this behaviour is allowed ?