Lesson 8
Making Objects the Main Star!
Chapter 3: Classes and attributes
Constructor with arguments
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
.
Examine the code below, and try running it yourself.
1 2 3 4 5 6 7 8 9 10 |
|
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 |
|
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
!