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.

4
  • 3
    Yes, python allows you to add new fields to the objects on the fly. Commented Jun 11, 2013 at 11:59
  • 2
    What's your question exactly? Commented Jun 11, 2013 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. Commented Jun 11, 2013 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. stackoverflow.com/a/32284457/6398487 Commented Dec 1, 2020 at 4:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the reply Sukrit. That Python Docs is simply too advanced for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.