Boss lesson · Unit 03
How methods work
Where self comes from, and the protocol behind property
What you practise
- Functions become bound methods through the descriptor protocol
classmethodandstaticmethod__slots____getattr__- A property built by hand
Try a question from this lesson
Pick one
The boss problem: where does self come from? Start by fetching the same method twice. What prints?
class Dog:
def speak(self):
return "woof"
d = Dog()
print(d.speak is d.speak,
d.speak == d.speak)Hint
If something were built fresh on each access, would two accesses give one object or two?
Correct answer
False True
Why
Each d.speak builds a new bound method: a small object pairing the function with d. Two accesses give two objects, so is is false, but they pair the same function with the same instance, so they compare equal.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A method is a function plus binding
A method is a plain function stored on the class. Functions have a __get__ method.
When d.speak finds the function on the class, Python calls its __get__ with the instance. The result is a bound method that remembers d and passes it as self.
class Dog:
def speak(self):
return "woof"
d = Dog()
f = Dog.__dict__["speak"] # a function
bound = f.__get__(d, Dog) # d.speak
print(bound()) # woofConcept
The descriptor protocol
Any object with a __get__ method, stored on a class, is a descriptor: attribute access through an instance calls __get__ and returns its result instead of the object.
Functions, property, classmethod and staticmethod are all descriptors. There is no other mechanism behind them.
class Ten:
def __get__(self, obj, owner):
return 10
class Box:
size = Ten() # lives on the class
print(Box().size) # 10: __get__ ran10 more exercises in the app
- 4× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× match the pairs
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.