Discussion 5

Links


Concepts

  1. What is the difference between a local name and an instance attribute?
  2. What are the lookup rules for dot notation?
  3. What does a subclass inherit from its superclass?
  4. What happens when a subclass has a method with the same signature as its superclass?

Problems

Question 1

Try out the WWPD at the end of this guide.

Question 2

Take a look at the two classes below and figure out what Python would output. Try drawing out a diagram to keep track of changing attributes!

class Random:
    x = 0

    def __init__(self, x, y):
        Random.x = x
        self.x = y

    def foo(self):
        return Random.x + self.x

class Randomer(Random):
    x = 3

    def bar(self, y):
        self.x = y
        return self.foo()
>>> a = Random(2, 3)
>>> b = Randomer(4, 5)
>>> a.x

>>> a.y

>>> Random.x

>>> b.bar(10)

>>> b.x

>>> Random.foo(a)

>>> a.bar(1000000)

TOGGLE SOLUTION

>>> a = Random(2, 3)
>>> b = Randomer(4, 5)
>>> a.x
3
>>> a.y
Error
>>> Random.x
4
>>> b.bar(10)
14
>>> b.x
10
>>> Random.foo(a)
7
>>> a.bar(1000000)
Error