Adding new member variables to python objects?

stgeorge picture stgeorge · Jun 11, 2013 · Viewed 15.9k times · Source

I have started reading the "Beginning python from novice to professional" by Magnus Lie Hetland, and what struck me today is an ability of an objects to create new member variables, even though those member variables were not present in the class from which the object was "created". Here is an example:

class Test:
    pass

b = Test()

b.variable1 = 12
b.variable2 = "Jim"

print b.variable1
print b.variable2

Until now I though that objects could only change the member values present in parent class, but not create new ones out of thin air? Btw I had no prior knowledge of programming or python.

Answer

Sukrit Kalra picture Sukrit Kalra · Jun 11, 2013

A similar example is given in the Python Docs. According to it, this notation is used for binding together a couple of named items. This is just what Python allows you to do.