What is a natural way to represent real-world “things” in code?
How can we organize code to make it easier to understand, test, and extend?
Are these the same thing?
A program is just another data structure.
[% figure slug=“oop-func-obj” img=“func_obj.svg” alt=“Bytes as characters, pixels, or instructions” caption=“Bytes can be interpreted as characters, pixels, or instructions.” %]
def defines a variable whose value is the function’s
instructions[%inc func_obj.py mark=def %]
[%inc func_obj.py mark=alias %] [%inc func_obj.out %]
[%inc shapes_original.py mark=shape %]
[%inc shapes_original.py mark=concrete %]
[%inc shapes_original.py mark=poly %]
[%inc shapes_dict.py mark=square %]
An object is just a (specialized) dictionary
A method is just a function that takes the object as its first parameter
[% figure slug=“oop-shapes-dict” img=“shapes_dict.svg” alt=“Storing shapes as dictionaries” caption=“Using dictionaries to emulate objects.” %]
[%inc shapes_dict.py mark=call %]
Look up the function in the object
Call it with the object as its first argument
obj.meth(arg) is
obj["meth"](obj, arg)
[%inc shapes_class.py mark=square %]
[%inc shapes_class.py mark=call %]
Look in the class for the method
Call it with the object as the first parameter
And we can now reliably identify objects’ classes
[% figure slug=“oop-shapes-class” img=“shapes_class.svg” alt=“Separating properties from methods” caption=“Using dictionaries to emulate classes.” %]
[%inc varargs.py %] [%inc varargs.out %]
[%inc spread.py %] [%inc spread.out %]
Shape that uses methods defined in
derived classes[%inc inherit_original.py mark=shape %]
[% figure slug=“oop-inherit-class” img=“inherit_class.svg” alt=“Implementing inheritance” caption=“Using dictionary search to implement inheritance.” %]
[%inc inherit_original.py mark=use %] [%inc inherit_original.out %]
[%inc inherit_class.py mark=shape %]
[%inc inherit_class.py mark=search %]
[%inc inherit_class.py mark=use %] [%inc inherit_class.out %]
[%inc inherit_constructor.py mark=shape %]
[%inc inherit_constructor.py mark=square %]
[%inc inherit_constructor.py mark=call %] [%inc inherit_constructor.out %]
[% figure slug=“oop-concept-map” img=“concept_map.svg” alt=“Concept map of objects and classes” caption=“Concept map.” %]