Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding new member variables to python objects?

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.

like image 413
stgeorge Avatar asked Jun 11 '13 11:06

stgeorge


People also ask

How do you add variables in Python?

The “+” operator is used to add the variables. The print(“The sum of variables “, variable) is used to get the output.

How do you assign a value to a class object in Python?

Use dot notation or setattr() function to set the value of class attribute. Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime. Python stores class variables in the __dict__ attribute.

What is __ add __ in Python?

The __add__() method in Python specifies what happens when you call + on two objects. When you call obj1 + obj2, you are essentially calling obj1.

What are member variables in Python?

In object-oriented programming, a member variable (sometimes called a member field) is a variable that is associated with a specific object, and accessible for all its methods (member functions).


1 Answers

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.

like image 173
Sukrit Kalra Avatar answered Sep 18 '22 03:09

Sukrit Kalra