Constructors
medium 45 minA constructor turns fresh, empty memory into an object that is ready to use.
Video lesson · Chapter 1 of 6
Make a prediction
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
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
It exists once.
Step 1: The class
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A default list in Python
criticalThe list is created once, with the function. All objects share it.
Wrongdef __init__(self, tags=[]): self.tags = tagsRightdef __init__(self, tags=None): self.tags = list(tags) if tags is not None else []Forgetting the parent
majorPython does not call the parent's constructor for you.
Wrongdef __init__(self, name, eid): self.eid = eidRightdef __init__(self, name, eid): super().__init__(name) self.eid = eidWork in the constructor
majorCreating the object in a test opens a connection, and a slow server makes creation slow.
Wrongdef __init__(self, url): self.db = connect(url)Rightdef __init__(self, db): self.db = dbHanding out self
criticalThe bus may call back before the next line has run.
Wrongdef __init__(self, bus, clock): bus.register(self) self.clock = clockRight@classmethoddef start(cls, bus, clock): alarm = cls(clock) bus.register(alarm) return alarmSetting before checking
minorIf somebody still gets hold of the object, it has bad values.
Wrongself.age = ageif age < 0: raise ValueErrorRightif 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