AlgoViz

Constructors

medium 45 min

A constructor turns fresh, empty memory into an object that is ready to use.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:45

See it run

Memory, arguments and order: what exists at each moment of creation.

Operations

A house is built

Class, order, memory, five fields, reference. Twelve small steps.

Step 1 of 11

The class

Houseclass: the plancolor?doors?windows?floors?roof?

The plan. It says which fields a house can have. There is no house and no value.

Step 1: The class

class House:    def __init__(self, color, doors, windows, floors, roof):        self.color = color        self.doors = doors        self.windows = windows        self.floors = floors        self.roof = roofmy_house = House("blue", 2, 4, 2, "peaked")
Shows
What new does
Remember
Reference comes last
Fields to set
5

self (or this) is the object that is being built right now.

In the real world

The same constructors doing real jobs. Pick one and step through it.

One plan, many independent objects.

Step 1 of 4

The class

Houseclass

It exists once.

Step 1: The class

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A default list in Python

    critical

    The list is created once, with the function. All objects share it.

    Wrong
    def __init__(self, tags=[]):    self.tags = tags
    Right
    def __init__(self, tags=None):    self.tags = list(tags) if tags is not None else []
  • Forgetting the parent

    major

    Python does not call the parent's constructor for you.

    Wrong
    def __init__(self, name, eid):    self.eid = eid
    Right
    def __init__(self, name, eid):    super().__init__(name)    self.eid = eid
  • Work in the constructor

    major

    Creating the object in a test opens a connection, and a slow server makes creation slow.

    Wrong
    def __init__(self, url):    self.db = connect(url)
    Right
    def __init__(self, db):    self.db = db
  • Handing out self

    critical

    The bus may call back before the next line has run.

    Wrong
    def __init__(self, bus, clock):    bus.register(self)    self.clock = clock
    Right
    @classmethoddef start(cls, bus, clock):    alarm = cls(clock)    bus.register(alarm)    return alarm
  • Setting before checking

    minor

    If somebody still gets hold of the object, it has bad values.

    Wrong
    self.age = ageif age < 0: raise ValueError
    Right
    if age < 0: raise ValueError(f"age {age}")self.age = age

Interview tips

  • Name the invariant

    • Say what is always true
    • Check it at the door
    • Make the fields final
  • One door

    • One constructor does the work
    • Factories only translate
    • The child calls super
  • Keep it boring

    • No network or threads
    • No overridable calls
    • this stays inside
  • Think of failure

    • Throw, do not return half
    • Roll back what is open
    • Test both sides of a limit