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-6).
1
2
3
4
5
6
7
8
9
10
11
12
13
class Person:
def __init__(self, firstname, lastname, age=0):
self.firstname = firstname
self.lastname = lastname
self.age = age
self.friends = []
person = Person("Josiah", "Wang", 20) # What do you mean I don't look 20? :D
print(person.firstname)
print(person.lastname)
person.age = person.age + 1
print(person.age)
Like a normal function, you may assign default values for any of the arguments (e.g. age=0
in Line 2)
Accessing/updating the value of the attributes is just like in C++, with a dot (.
) operator (Lines 9-13)
The attributes are public by default. What about private attributes? Hold that thought, we’ll come to that later!