Exercises, examples and other material relating to training module Y112. This topic is presented on public courses
Python supports object inheritance and all that that implies, such as polymorphism. This module shows you how inheritance works in Python.
|Articles and tips on this subject||updated|
Python's decorators allow you to wrap a function within another. You might want to do this to report on or log some of your functions, to set timers, or to add other behaviousr to a whole group of functions. Decorators also allow you to modify the calling sequence to your methods (but be careful!); ...
|4718||Defining an object that is a modified standard type in Python|
If you want an object that behaves like a regular standard object but with the odd exception, you can define your own class which inherits from the system type. For example, we have redefined a dict as a specialDict in an example [here] where we've overridden just the __str__ method so that when we ...
|4717||with in Python - examples of use, and of defining your own context|
The with keyword in Python lets you set up an object with a block scope and a defined closure. It's implemented in the standard file handle object library - see example at [here] and you can implement it for your own object using the __enter__ and __exit__ methods - example [here]. Note that the __exit__ ...
|4649||Object and Static methods - what is the difference; example in Python 3|
There are two types of methods (named pieces of code) that you can use in a class.
Object methds - occasionally called dynamic methods - operate on an object within a class ("one particular thing of a type") and will always have some way of referencing the elements (variables) within an object of the ...
|4541||Setting up and tearing down with the Python with keyword|
Python's with operator lets you set up and tear down an object for use in a bock of code - typically useful for a file handle / resource accessor. Here's an example of it in use:
with day() as today:
print ("Today it is " + today)
It's set up using the __enter__ ...
|4450||Deciding whether to use parameters, conditional statements or subclasses|
"If you find yourself repeating a piece of code, there must be an easier way" But what if you have a number of similar but not identical items / things / objects?
If the things that change between each of your objects are just data values - for example the number and ages of childen - then you can handle ...
|4449||Spike solution, refactoring into encapsulated object methods - good design practise|
Initial test code on new data sets - your research work - will most likely take place in smaller chunks of code while you work out just how the data flows and what you need from it (and you are remembering to read documentation supplied by the data originator, aren't you??).
But having done that initial ...
|4410||A good example of recursion - a real use in Python|
Recursion is where a named block of code calls itself. The "classic" demonstration is the code to generate a factorial number:
if n ...
|4366||Changing what operators do on objects - a comparison across different programming languages|
In Object Oriented languages, you used named pieces of code known as methods to perform an operation on a variable - for example you might write
to take a list of (something) for a week and add a list relating to weekend onto the end of it.
Sometimes, the method ...
|4356||Object factories in C++, Python, PHP and Perl|
Raw materials are converted into a manufactured product in a factory or by a factory procedure, and the sort of product you can make depends on both the raw material that's supplied and on the capability of the factory.
And so it is with Object Oriented Computer Programming - supply raw material ...
|4344||Python base and inherited classes, test harness and unit testing - new examples|
From a recent Python course ... a new series of examples on writing, testing and using classes. The customer is using Python 2.6 and 2.7, so the code is written with what we call "new style classes" where everything eventually inherits from a base class os object - with that eventual inheritance expected ...
|4094||Python Properties - how and why|
When you're being taught Object Oriented Programming, you'll usually be encouraged to access all the various elements within each object through methods rather than by going directly at the variables that hold properties within the object directly. And yet this will often result (depending on the language) ...
|4028||Really Simple Class and Inheritance example in Python|
It's so tempting when writing a simple training example to get excited and add lots of features - so that you then end up with an example that's anything but a simple training example!
Here's an example - just about my shortest and simplest ever - that shows a base class, a subclass, inheritance, polymorphism, ...
|3887||Inheritance, Composition and Associated objects - when to use which - Python example|
• Inheritance is where one object is based on another.
• Composition is where one object contains another.
Question: Which should I use?
Answer: Probably BOTH!
On yesterday's Python course, the question came up, and I wrote an illustrative answer - source code [here]. The scenario we ...
|3796||Backquote, backtic, str and repr in Python - conversion object to string|
The backquote or backtic operator in Python is a pseudonym for the repr function.
If you have an object that you want to convert into a string (to manipulate it, store it, print it out), Python may call one of two standard method:
__str__ (also the str function) converts an object into a human-readable ...
|3524||Metaclasses (Python) and Metatables (Lua)|
"A Metaclass (Python) or Metatable (Lua) adds extra code / data / behaviour to an object, table, or class."
What does that mean? It means that I can define a behavior that I want to be shared, that I want to define at run-time, that I want to amend ... in a separate module / zone / table from my main ...
|3472||Static variables in functions - and better ways using objects|
Usually, I don't want leftovers from a previous call to a function to hang around when I call the same function again later in my program. After all, the cosine of 45 degrees is not dependent on what the previous cosine request I made was! However, there are some occasions where I may want to have ...
|3442||A demonstration of how many Python facilities work together|
Many of our demonstrations on the Well House Consultants site show individual features of a language - taken in isolaion to show you how they work. However, during a course we usually write further examples to show you how features work in combination to give a total result / solution to an application.
|477||Class, static and unbound variables|
In Object Oriented programming, you'll have certain named blocks of code (usually known as methods) that you can perform on specific objects (type A), and others that you can perform on all the objects of a particular type (type B).
If I had a class called sandwich, I might have one method ...
|3002||A list of special method and attribute names in Python|
If I write
a = b + c
in Python, I'm really writing
a = b.__add__(c)
(see source code example [here]
In other words, every variable is an object and every operator is a method. It's just the icing on the cake that makes the language as powerful as it is - with the clever engine ...
|2994||Python - some common questions answered in code examples|
Some tips and new examples from last week ... Python in Plymouth!
• How do I put comments in a Python regular expression to make it more readable: [source]
• How do I use a python dictionary as a table of counters - in our example, counting the number of people in our team who have each of ...
|2905||Defining static methods in Python|
If you define a method within a class, it defaults to being a dymanic method - in other words, one which runs on an object that's a member of the class. If you want to define a method that applies to the class as a whole, you're looking for a static or class method - and in Python you can set one of ...
|2889||Should Python classes each be in their own file?|
Should classes each be defined in a file of their own? In Java, unless you're making a use of inner classes, you're coerced into writing one class per file. In C++, you'll typically have the code for a class in one source file and the headers in another, as other schemes are impractical to use and ...
|2785||The Light bulb moment when people see how Object Orientation works in real use|
A big "light bulb" moment for many customers is when they "get" object inheritance. And one of the best ways of explaining it is by writing an example.
On Wednesday, I wrote an example during our Python Course - taking a customer of Well House Consultants as my base class, then defining two extended ...
|2720||Multiple inheritance in Python - complete working example|
Python supports multiple inheritance, but good simple examples are very hard to find. So here is an example which I wrote during my trip to Ireland, where I was running a private Python course (link - Python courses).
I've defined two base classes - a "transport object" that provides a method to return ...
|2764||Python decorators - your own, staticmethod and classmethod|
Python Decorators are wrappers that you may apply around methods. So they're rather like the bread around a sandwich.
There are a number of standard decorators provided with Python - such as @classmethod and @staticmethod (see [here]) which allow you to turn methods into unbound (static, class) ones. ...
|2722||Mixins example in Python|
Mixins allow you to add ("Mix in") code - usually shared code - from one class or module into another. They're a great way of providing great "light weight" multiple inheritance - I wrote about that [here] recently, and provided an example in Ruby to show how it works.
Mixins can also be used in Python ...
|2717||The Multiple Inheritance Conundrum, interfaces and mixins|
Should an OO programming language support "multiple inheritance"? Let's define multiple inheritance first - starting from simple (single?) inheritance.
I don't want to have to define each type of thing ("class of object") from scratch, so I'll define once class as being based ...
|2693||Methods that run on classes (static methods) in Python|
• If you want to write a class or static method in Python, you can write an object (or dynamic) method and then call the classmethod function to make it into a method that can additionally run on the the class as a whole:
# This is a 'dynamic' method
|2485||How do I set up a constant in Python?|
You may think of values like pi being a constant, but in Python they're really just another object that's defined in the namespace of the module from which they're loaded!
>>> import math
>>> math.pi *= 4
You are fully entitled to ...
|2409||TypeError: super() argument 1 must be type, not classobj (Python)|
If you've got an error message like this, you've called up a method from the base class of your object using "new style classes", but the base class is an "old style class". The full error message looks something like this:
Traceback (most recent call last):
File "cl_n.py", line 24, in ...
|2368||Python - fresh examples of all the fundamentals|
Some more new examples in Python - from this week's course.
From my Introduction to Python / simple example to show the power of the language, I present my example that parsed a big data (log) file and counter and sorted by number of accesses the hits from various remote hosts. A long report, ending ...
|1819||Calling base class constructors|
In all object oriented languages, you have a facility called inheritance where you can define one type of thing ("class of object") based on another, and the newly defined class ("subclass" or "extended class") takes the initial ("base") class as it starting point.
In your code for your base class, ...
|1661||Equality, sameness and identity - Python|
Is the number 7.0 the same as the number 7.00000? A trick question, because it depends on how you look at it. It has the same value, but it is not identical. And if eachof them is held in computer memory, there's no chance at all that they're both the same thing - i.e. held in the same memory location ...
|1644||Using a utility method to construct objects of different types - Python|
When you call an object's constructor method, you'll be allocating memory to hold the information about that object and the method will return an instance variable - a reference with which you can later refer back to the object.
That's good as far as it goes - but there are times when you'll have data ...
|1517||Python - formatting objects|
If you're going to be printing out objects from within Python, simply provide an __str__ method in the class and it will do all the work for you. Indeed - why not create classes and objects for straightforward objects such as people's names ... then you can call up the formatter for them very easily ...
|1217||What are factory and singleton classes?|
Do you find some of the OO terminolgy baffling? Once you've learnt about constructors and methods, inheritance, overloading and polymorphism and statics, you might think you're there. Then someone mentions a "factory class" or a "singleton" ...
Fear not - factory and singleton classes are posh names ...
|1146||__new__ v __init__ - python constructor alternatives?|
The constructor you'll normally override (and call when you create an object) in Python is called __init__, but there is also a method called __new__ available to the class author.
If __new__ is defined on a class, it is called in preference to __init__
With __new__ you return the object you have constructed, ...
|964||Practical polymorphism in action|
Polymorphism is the ability of a piece of common code to process a piece of data in different ways depending on its type. It's a great facility, talked about a lot in theory and on courses ... but then what about its practical use? Here's a very simple little example from last week, showing how ...
|903||Pieces of Python|
From a most interesting Saturday which was spent doing a one on one session on thread, wxPython, etc - some Python snippets that provide unusual demos and hard-to-find answers:
The Backtic operator evaluates an expression and returns the result as a string
val1 = 16
val2 = 18
result = "The result ...
|831||Comparison of Object Oriented Philosophy - Python, Java, C++, Perl|
There are two different philosophies that have been adopted by the authors of Object Oriented languages.
The first approach is to set the thing up in such a way that a programmer who uses someone else's code as the basis for his isn't going to be trusted to use that other person's code in a sensible ...
|656||Think about your design even if you don't use full UML|
Even if you don't feel that your project is big enough to get involved with formal design methods, many of the lessons of UML and some informal design diagrams can help you get a clear view of what you're going to be doing be for you start, and can help you come up a good, thought out and reliable plan ...
|accom.py|| Accommodation base clase|
|accom_finder.py|| Sample application using hotel and bandb|
|accoms.xyz|| Sample data for accoms program|
|addload|| Illustration of how the + (add) operator is really defined|
|alog|| objects within objects - access log hits and visits|
|bandb.py|| definition of subclass bandb of accom|
|boxex|| Overloading (redefining) addition and how a variable is printed|
|bq|| backquote / backtic operator |
|c1.py|| Classes, subclasses, static method, test harness|
|cbx|| Callbacks in Python|
|cho|| New style class - with inheritance|
|cho.py|| new style classes, as module with inheritance and test harness|
|cl_n.py|| New Style classes and inheritance|
|cl_o.py|| Old Style classes and inheritance|
|clever|| nested decorators|
|dayzend|| using with to open and close an object|
|end_of_universe.txt|| Data for p4.py example|
|fcl.py|| program to show use of "person" class|
|goat.py|| Defining a class of goats and overriding addition|
|hotel.py|| definition of subclass hotel of accom|
|hound.py|| Definition of two objects to demonstrate polymorphism|
|id|| getitem and getslice|
|looob2|| class exercise - add 200 count please|
|m_i_m|| Mixins Complete Example|
|mcx|| metaclass setup and use|
|meerkat|| Decorator v modifier; static methods|
|mi|| Multiple Inheritance|
|mult_inherit|| Multiple Inheritance Complete Example|
|ob1.py|| definition and use of property with lambda|
|obob|| Inheritance demo|
|overload_add.py|| Operator (+) and to_string overloading, Python|
|p4.py|| Factory, comparator, inheritance etc|
|people.py|| Class, subclasses, test harness. Inheritance, Poymorphism and Overloading|
|person.py|| Class with Body Mass Index method|
|personx.py|| OO demo - multiple classes, inheritance, test program|
|pets.py|| Simple base class, subclass and polymorphism|
|pub.py|| wholesale factory method - read file to list of objects|
|pysin|| Singleton class |
|restex.py|| Class example - restaurant|
|taball|| all together table example|
|tabledata.csv|| Data file for Python 3.4 inheritance model|
|tables.py|| Python 3.4 tables interitance and factory demo|
|teapot.py|| Class heirarcy in a single file|
|thems|| Polymorphism demonstration - uses cat and dog objects from hound.py|
|timetable.txt|| data for pub.py|
|ting2|| static (class) methods via decorators|
|tr1.py|| class, subclass, utility, factory, etc|
|travel.py|| static methods, overloaded operator, propertys, inheritance and polymorphism ...|
|travel.txt|| Data file for "tu2" example|
|triang.py|| definition of a property|
|ttest.py|| calling an attribute [property]|
|tu2|| Sample program (2) using c1.py demonstration classes|
|tuse|| Sample program (1) using c1.py demonstration classes|
|ub|| Utility method to construct different objects|
|ufd|| Sample data for person.py demo|
|whm_real|| Factory method |
|xmc4.py|| Polymorphism and inheritance with Christmas and Easter Characters|
|yum|| Define your own add and print methods|
Pickling and shelving objects.
Old Style Objects (prior to Python 2.2)
If you are looking for a complete course and not just a information on a single subject, visit our Listing and schedule
Well House Consultants specialise in training courses in
. We run
throughout the UK (and beyond for longer courses), and
at our training centre in Melksham, Wiltshire, England.
It's surprisingly cost effective to come on our public courses -
even if you live in a different
country or continent to us
We have a technical library of over 700 books on the subjects on which we teach.
These books are available for reference at our training centre.