Exercises for Lesson 21

Back to Lesson 21

Exercise 1: Inheritance and method calls

Let’s dive into graphics.py, which is a fantastic example of object-oriented design.

Part a: Family trees

There are over 10 classes related to shapes and the window. Make a diagram just showing the parent-child relationships between classes in graphics.py.

Part b: Circle.draw

Using your diagram, look through different class definitions. In which class is the .draw() method of a Circle defined?

Part c: Circle.getCenter

Using your diagram, look through different class definitions. In which class is the .getCenter() method of a Circle defined?

Back to Lesson 21

Exercise 2: Inheritance and method calls

The following program defines four classes. Draw a class diagram indicating the relationship between classes, as well as each class’s instance variables, constructor, and other methods.

class A:
    def __init__(self, val):
        self.value = val # not a bug -- these don't have to match!

    def doTheThing(self):
        print("In A:", self.value)

class B(A):
    def doTheThing(self):
        print("In B:", str(self.value) * 2)

class C(A):
    def __init__(self, value):
        self.value = value * 2 # set self.value ourselves

class D(A):
    def __init__(self, v, otherVal):
        self.value = v
        self.otherVal = otherVal

    def doTheThing(self):
        print("In D:", self.otherVal * self.value)

def main():
    a = A(4)
    b = B(22)
    c = C(55.1)
    d = D(10, 7)

    for obj in [a,b,c,d]:
        obj.doTheThing()

if __name__ == "__main__":
    main()

Back to Lesson 21