It's a bad idea in general to use obj.__dict__
because the object dictionary does not contain any descriptors or other "magic" attributes that may exist on the object. It will also include hidden attributes that, by convention, are hidden behind a _
prefix. Thus, the obj.__dict__
technique really only works for completely basic types, and is not future proof if you decide to update any attributes to be properties so that you can control their getters/setters, etc. vars(obj)
has this same issue.
class Rectangle(object):
x = 0
y = 0
_width = 0
height = 0
@property
def width(self):
return self._width
@width.setter
def width(self, value):
if value < 0:
value = -value
self.x -= value
self._width = value
>>> r = Rectangle()
>>> r.__dict__
{}
>>> # this is because everything is class-level properties so far
>>> r.width = 50
>>> r.__dict__
{'_width': 50}