Lesson 1 · Unit 03
Attributes
Instance or class, properties, and what super() really calls
What you practise
- Instance against class attributes, the shared class-level list, properties, the method resolution order and what
super()really calls
Try a question from this lesson
Pick one
Two teams are created, and a member is added to one of them. What prints?
class Team:
members = []
def add(self, name):
self.members.append(name)
a, b = Team(), Team()
a.add("ada")
print(b.members)Hint
The list is created when the class body runs. How many times is that?
Correct answer
['ada']
Why
The class body runs once, so there is one list, stored on the class. self.members finds nothing on the instance, falls back to the class and mutates that shared list. Every team sees every member.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Read looks up, write stays put
Reading obj.attr searches the instance's own dict first, then the class, then its base classes.
Writing obj.attr = value never searches: it stores on the instance, even when the class already has that name. The class value is then hidden for that one object.
class Dog:
legs = 4 # on the class
d = Dog()
d.name = "Rex" # on the instance
print(vars(d)) # {'name': 'Rex'}
print(d.legs) # 4, found on DogConcept
Properties
A property is a method that is read like an attribute: no brackets, computed on every access.
Add a setter and assignment runs your code too, which is where validation goes. Callers cannot tell a property from a plain attribute, so you can add one later without breaking them.
class Temp:
def __init__(self, c):
self.c = c
@property
def f(self):
return self.c * 9 / 5 + 32
t = Temp(100)
print(t.f) # 212.0, no brackets
t.c = 0
print(t.f) # 32.0, computed on read10 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 2× fill the blanks
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.