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|
|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|
|bandb.py|| definition of subclass bandb of accom|
|boxex|| Overloading (redefining) addition and how a variable is printed|
|bq|| backquote / backtic operator |
|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|
|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|
|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 |
|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|
|travel.py|| static methods, overloaded operator, propertys, inheritance and polymorphism ...|
|triang.py|| definition of a property|
|ttest.py|| calling an attribute [property]|
|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|
A first example of inheritance in Python.
A further example.
Classic and new-style classes.
Attributes and properties.
Finding out about the class of an object.
A practical example of overloading operators.
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. Also
available is the Opentalk
Forum for discussion of technical questions.