Constructor¶
Motivation¶
Manually setting attributes (as in Classes And Dictionaries) is clumsy
Typos/bugs ahead
⟶ want a well-defined object initialization
⟶ want to require user to pass
firstname
andlastname
class Person:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
Calling the type ⟶
__init__()
person = Person('Joerg', 'Faschingbauer')
f'firstname: {person.firstname}, {person.lastname}'
'firstname: Joerg, Faschingbauer'
And self
?¶
class Person
⟶ object of typetype
Types are callable ⟶ creates instance
If class has
__init__
method defined, then that is called to initialize the objectInvoked with two parameters
person = Person('Joerg', 'Faschingbauer')
Called with three parameters
class Person: def __init__(self, firstname, lastname): ...
The object being constructed
The instance under construction
Object being initialized:
self
(nameself
is only convention)