Bitpath

Boss lesson · Unit 03

How methods work

Where self comes from, and the protocol behind property

13 exercisesabout 3 min

What you practise

  • Functions become bound methods through the descriptor protocol
  • classmethod and staticmethod
  • __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?

Python
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?

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.

Python
class Dog:
    def speak(self):
        return "woof"

d = Dog()
f = Dog.__dict__["speak"]  # a function
bound = f.__get__(d, Dog)  # d.speak
print(bound())             # woof

Concept

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.

Python
class Ten:
    def __get__(self, obj, owner):
        return 10

class Box:
    size = Ten()     # lives on the class

print(Box().size)    # 10: __get__ ran

10 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.

One email when Bitpath is ready to try. Nothing else. Privacy