This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: Classes and attributes

Constructor with arguments

face Josiah

Let’s make your Person class a bit more useful! Let’s allow the programmer to initialise with some attributes.

For simplicity, we assume that a Person object has three instance attributes: name, age, and nationality.

Class diagram

Examine the code below, and try running it yourself.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Person:
    def __init__(self, name, age, nationality="uk"):
        self.name = name
        self.age = age
        self.nationality = nationality

manager = Person("Josiah", 20, "malaysia")
print(manager.name)
print(manager.age)
print(manager.nationality)

Line 7 will allocate new 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.

You are free to do more than just assigning values to attributes. For example, you could try to load information from a database, initialise something other attributes (maybe generate an ID?), or check whether a value is valid.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Person:
    def __init__(self, name="Anonymous", age=0, nationality="uk"):
        self.name = name 

        if age < 0:
            raise ValueError("age must be at least 0")
        else:
            self.age = age

        self.nationality = nationality

raise ValueError (Line 6) means that you are purposely causing an exception to happen, with a custom error message. Note that ValueError is also a class, so you are actually creating a new instance of ValueError!