Python for C++ Programmers
Chapter 8: Object-oriented programming
Attributes
Let us now look at how you declare and initialise instance attributes (or instance variables), as well as use it.
In C++, you declare instance variables/attributes directly in the class declaration.
In Python, you dynamically attach new instance variables to the self object inside __init__() (remember that self has only been allocated some space in memory at this point). This is where you initialise any attributes and their values (Lines 3-5). Examine the code below, and try running it yourself.
1 2 3 4 5 6 7 8 9 10 11 | |
Line 7 will allocate new heap memory space for the Person instance, and then pass on the arguments "Josiah", 20, and "malaysia" to Person.__init__(). Note that while the first parameter for __init__() is self, you do NOT need to pass it because it will be done automatically. Therefore, your first argument "Josiah" is for the second keyword parameter name, 20 for the third keyword parameter age, etc.
Lines 3-5 will then assign attributes (and values) to the object. Think of self as a mutable object, to which you can directly add attributes. After executing the method, Python will automatically return self to the original caller.
Like a normal Python function, you may assign default values for any of the arguments (e.g. nationality="uk" in Line 2).
Accessing/updating the value of the attributes is just like in C++, with a dot (.) operator (Lines 8-11).
The attributes are public by default. What about private attributes? Hold that thought, we’ll come to that later!