Interfaces and protection

Interfaces

An interface is a blueprint of the methods that a particular class should implement. A programmer knows what methods a class that implements a certain interface will perform but not how they will be carried out. Perhaps in implementing a game you would create an interface called Movement that implemented the methods move_forward, move_backwards, move_left and move_right. Each sprite that implemented the interface could define its own method allowing them to move differently. Python doesn't have built in support for interfaces like other languages e.g. Java or C#, but it can still be achieved through Duck Typing and abstract base classes or ABCs for short.

Duck typing

Duck typing refers to the expression "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck." This means that even though there is no method specifically for providing an interface, we can make something that behaves like one. The make_it_speak method expects its parameter to be an object with a speak method. We don't need to explicitly say an object implements a method as any method that has the required method in it, in this case speak(), fits the interface and can use the method.



Abstract base classes

Abstract base classes are the explicit way to define an interface in Python. We import the abstract base class module and create a specific abstract base class by passing ABC as the argument. All this says is that any class inheriting the Animal abstract base class must implement its methods.



Private, protected and public

Private

Private methods and attributes are available only from within the class where they are defined. Most attributes are private so they have to be accessed and modified via their methods.

Protected

Protected methods and attributes are available from within the class where they are defined and subclasses of that class. Methods and attributes that are inherited by a subclass will be protected rather than private so they are accessible to the child class.

Public

Public methods and attributes are available from within the class where they are defined, subclasses of that class and from outside the class by reference to an instance of that class e.g. cow.speak( ).

Most methods are public so that other objects can use these to interact with the objects. Private and protected methods would be used for methods that perform functions that are only ever required within the class.



In UML diagrams attributes and methods are marked with:
(-) private, (#) protected, or (+) public



Knowledge check


Questions:
Correct:

Question text


© All materials created by and copyright S.Goff