17

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.

stgeorge
  • 483
  • 3
  • 7
  • 16
  • 3
    Yes, python allows you to add new fields to the objects on the fly. – Andrew Jun 11 '13 at 11:59
  • 2
    What's your question exactly? – mgilson Jun 11 '13 at 12:05
  • 1
    Sorry for being unclear. The upper code (or principle) was not in the book, I discovered it by accident. So I just thought I might got something wrong. Andrew confirmed that this is not the case. So I guess that's just what I wanted to know. Thank you. – stgeorge Jun 11 '13 at 12:13
  • This person gives a hint. For C user, such behavior is disallowed because C requires the exact memory size to be specified, but the mechanism in python is different, which is just a dictionary that specifies the instance name and value without bothering the memory size. https://stackoverflow.com/a/32284457/6398487 – Jason Dec 01 '20 at 04:47

1 Answers1

9

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.

Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71