Object Philosophy

Dr Andy Evans

[Fullscreen]

  • Object Orientation aspires to three philosophical approaches.
    • Encapsulation: the notion that data and the procedures to work on them are within a class, and that external code should only access both in controlled ways.
    • Polymorphism: the notion that objects should work with multiple data types invisibly coping with whatever is thrown at them.
    • Inheritance: the idea that classes should be built in a hierarchy of increasing complication, each layer automatically picking up the more generic behaviour of the parental code in the hierarchy.

Encapsulation

  • Python is mixed bag with regards encapsulation. As a high level language much is hidden, but if you want to encapsulate your own classes it's less helpful at keeping people out of your code.
  • We've seen within an object that instance variables can't be accessed directly, which is good encapsulation practice.
  • But it is hard to prevent other code accessing instance variables directly, which is bad practice (how do we know what a variable is doing in other code when we change it?).

Polymorphism

  • We've seen that functions will often take in a wide variety of data types, that is, Python has parametric polymorphism, or "Duck Typing" "If it looks like a duck, and quacks like a duck, it can be treated like a duck."
  • This renders the standard approach to polymorphism (overloading, or "ad hoc polymorphism": to have multiple methods with the same name and let the runtime decide which to call based on the argument types) less necessary, and Python won't generally allow methods with the same name in the same class.
  • We can't forget, however, that different data types will result in very different operations: a function that adds two variables will have very different results for two numbers compared to two strings.

Inheritance

  • There are two areas to get our heads around with inheritance.
  • The first is the development side: how and why do we build inheritance hierarchies?
  • The second is on the use side: how do we use inheritance?

Why inherit?

  • Inheritance allows us to structure code appropriately.
  • We can build code that matches natural hierarchies, with different behaviour at each level.
  • It also allows us to pick up code without effort.
  • By inheriting, we gain all the code from the parent class invisibly.
  • Each level inherits the code above it.
UML of the relationships described

Terminology

  • In standard Object Orientation, we talk about a subclass inheriting from a superclass.
  • We may also, informally, talk about a child class inheriting from a parent class.
  • In Python, the terminology is generally a derived class inheriting from a base class.

Inheritance

  • Different inheritance constructions:
    class MySuperClass(type): # Generic inheritance
        pass

    class MySubclass(MyClass): # Objects of MySubclass
        pass # inherit MyClass

    class MyClass(metaclass=MySuperClass): # Class of a class
        pass

Overiding

  • While it is usual for subclasses to pick up and use super class methods and variables, it can override them.
  • Note that if you do so, any superclass method inherited into the class will also call the subclass version, which can cause issues.
  • The derived class is searched before the base class.

Calling superclass methods

  • If the derived class wants to directly access a superclass method or variable, overridden or not, it can use the super keyword:
    super.variable_name
  • If you need to call a superclass init (because it needs the variables), do this:
    super().__init__([args...])
  • To call more general methods:
    class Derived(Base):
    def meth(self):
    super(Derived, self).meth()

Multiple inheritance

  • There is nothing to stop you inheriting from multiple classes:
    class DerivedClassName(Base1, Base2, Base3):
    (though this may not always work in practice: what does it mean to be both a menu and a button, for example?).
  • Variables and methods are searched for broadly depth first, left to right; so Base1 is searched, and all its base classes, then Base2, etc.

issubclass

  • Just as isinstance tests whether an object is of one or more classes,
    issubclass(class, classinfo)
    will identify whether classes subclass another.

Class quirks

  • Overriding is where one element in a class within a class hierarchy over writes another with the same name. It is a key element of inheritance, allowing code to replace parental code, but it can cause issues.
  • Variables in a class will quite happily override methods with the same name, so make sure your naming system doesn't encourage this. The docs suggest using nouns for variables and verbs for methods.

Inheritance and arguments

  • Inheritance allows for "Duck Typing" through invisibly picking up methods and variables (formally Subtyping). Essentially for functions expecting a particular class of object (the supertype), you can pass in sub-classes (subtypes) knowing that they will look right; i.e. "If it looks like a duck, and quacks like a duck, it can be treated like a duck."
    def is_further_from_equator_than(self,other):
        if (self.x > other.x): return True
        else: return False

    print(dog.is_further_from_equator_than(cat))
    Where dog and cat inherit and instantiate Agent.

Subtyping

  • One key use for subtyping is in Design by Contract contract formation.
  • A contract (or sometimes "interface", though notes the more general API) is a statement that certain methods and variables will be present within objects.
  • If we can make these promises, methods that work with the objects can guarantee that they will work with the objects.
  • For example, the Windows Operating System is held together by the Component Object Model, based on such contracts. These allow programs to send each other method requests and data knowing they can be dealt with (e.g. you can embed Excel tables into Word).

Subtyping

  • Traditionally if you inherited a class you essentially guaranteed you had the methods it had, which means subtypes could replace for the supertypes in method calls.
  • In manifestly typed systems, a method can check a argument inherits a supertype, and allow it in.
  • Moreover, a class can inherit from an abstract class that has no implementation, with the manifest typing compiler not compiling unless the promised methods and variables are implemented in the subtype.

Contracts

Overriding standard methods

  • One way in which Python stays so high-level is by implementing a lot of complicated behaviour in dunder (double underscore - double underscore) methods.
  • In general the most common one to come across is __init__.
  • But there are many others that you can override to change default behaviours. These are inherited from the standard "object" all classes invisibly inherit.
  • For example, operators like "+" call dunders within objects to work, meaning you can change how standard operators work for your classes/objects. https://docs.python.org/3/reference/datamodel.html

Standard methods to override

  • Other than __init__ another standard method to override is:
    object.__str__()
  • Should return a nice string describing the object or its contents.
    def __str__(self) :
        return "Hi I'm an agent"