class Boo():pass var1 = Boo var1.x = 4 How is this possible

Classes have a __dict__ by default, precisely for this purpose (run-time assignment and modification of attributes). Regular attribute assignment just puts the corresponding names and values values in there.

It’s no different from setting it at class definition time, really:

>>> class Boo:
...     x = 1
>>> Boo.y = 2
>>> Boo.__dict__
mappingproxy({'__dict__': <attribute '__dict__' of 'Boo' objects>,
              '__doc__': None,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'Boo' objects>,
              'x': 1,
              'y': 2})

This way, you can contribute methods and variables to classes after the class has already been defined, and it will effect pre-existing instances of that class. If you hear of someone saying Python is a dynamic programming language, what you’re seeing here is one aspect of what the term dynamic actually means in this context.

Browse More Popular Posts

Leave a Comment