Defining attributes
Now, since the constructor is the first method to be called when you create a new instance of an object, we can use it to initialise anything we like for the object.
So, let’s say a Person
should have a name
and an age
. So we can use the constructor to initialise their values.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
So we will assign a value to the attributes name
and age
of the newly created object (i.e. self
).
An instance of a Person
will now have the instance attributes name
and age
, accessible using a dot operator (.
)
Instance attributes describe the properties (what an object has) and the states of the object.
lecturer = Person("Josiah", 20) # What do you mean I don't look like I'm 20? :D
print(lecturer.name)
print(lecturer.age)
Of course, you may assign default parameters to the method as in functions.
Class attributes
A class can also have class attributes. Here, the attribute belongs to the class (e.g. Person
) and not to the class instance (e.g. the object lecturer
refers to).
The attribute is bound to the class, and not to the instance. The value is shared among all instances of the class.
You can access a class attribute either with ClassName.attribute
or instance_name.attribute
. The following example makes it clearer.
class Person:
count = 0 # class attribute
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age # instance attribute
Person.count += 1
lecturer = Person("Josiah", 20)
print(Person.count)
print(lecturer.count)
assistant = Person("Luca", 18)
print(Person.count)
print(lecturer.count)
print(assistant.count)
So in this case, Person.count
acts as a ‘global’ counter that keeps track of how many instances of Person
has been created.