I have been told that declaring dynamic attributes within a classes scope is not the ‘Python Way’ but I do not understand why.
Could someone explain this to me or point me at some documentation as to why this is a bad thing? Honestly, I thought this was good practice, if anything for self documenting code.
Example:
class ClassA(object):
user_data = {}
def set_user(self):
self.user_data['username'] = 'fred'
The only reason I can see for not using this is that attributes are static (and so could be misleading)..
With the code as shown,
user_dataisn’t a dynamic attribute (It’s not created on the class instance “dynamically”). It’s a class attribute which is a lot more like “static” attributes in some other languages I believe. This means that it is an attribute declared on the class at the time the class is read and initialized. This has the side-effect/benefit of all of the instances being able to access the same object viaself.whatever.In other words:
will always print
True. Of course, you can change this behavior by adding a differentwhateverattribute to an instance:With
Foo, if I add items:foo_instance.whatever['foo'] = 'bar', thenfoo_instance2will see that change as well, whereas that won’t be the case withBar.