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 and lastname

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 type type

  • Types are callable ⟶ creates instance

  • If class has __init__ method defined, then that is called to initialize the object

  • Invoked 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 (name self is only convention)