Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
For 2023 - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))

Well House Consultants
You are on the site of Well House Consultants who provide Open Source Training Courses and business hotel accommodation. You are welcome to browse and use our resources subject to our copyright statement and to add in links from your pages to ours.
Other subject areas - resources
Java Resources
Well House Manor Resources
Perl Resources
Python Resources
PHP Resources
Object Orientation and General topics
MySQL Resources
Linux / LAMP / Tomcat Resources
Well House Consultants Resources
Extras Resources
C and C++ Resources
Ruby Resources
Tcl/Tk Resources
Web and Intranet Resources
Python module Y112
Objects - Intermediate
Exercises, examples and other material relating to training module Y112. This topic is presented on public courses Learning to program in Python, Python Programming, Intermediate Python

Python supports object inheritance and all that that implies, such as polymorphism. This module shows you how inheritance works in Python.

Related technical and longer articles
all variables are objects

Articles and tips on this subjectupdated
4719Nesting decorators
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!); ...
4718Defining 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 ...
4717with 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__ ...
4649Object 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 ...
4541Setting 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__ ...
4450Deciding 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 ...
4449Spike 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 ...
4410A 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:   def factorial(n):     if n ...
4366Changing 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   weeklist.extend(weekend) to take a list of (something) for a week and add a list relating to weekend onto the end of it. Sometimes, the method ...
4356Object 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 ...
4344Python 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 ...
4094Python 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) ...
4028Really 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, ...
3887Inheritance, 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 ...
3796Backquote, 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 ...
3524Metaclasses (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 ...
3472Static 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 ...
3442A 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. On ...
477Class, 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). Example. If I had a class called sandwich, I might have one method ...
3002A 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 ...
2994Python - 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 ...
2905Defining 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 ...
2889Should 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 ...
2785The 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 ...
2720Multiple 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 ...
2764Python 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. ...
2722Mixins 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 ...
2717The 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. (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 ...
2693Methods 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: def counter(cls):    # This is a 'dynamic' method    return ...
2485How 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! So ... >>> import math >>> math.pi 3.1415926535897931 >>> math.pi *= 4 >>> math.pi 12.566370614359172 You are fully entitled to ...
2409TypeError: 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 ...
2368Python - 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 ...
1819Calling 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, ...
1661Equality, 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 ...
1644Using 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 ...
1517Python - 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 ...
1217What 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, ...
964Practical 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 ...
903Pieces 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 ...
831Comparison 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 ...
296Using a Python dictionary as a holder of object attributes
Have a great bank holiday, folks. For any sad (or happy) Python programmers out there, here's a simple example of __getattr__ in use. I've got an object of type thingy with all its atributes held in a dictionary, but I wanted to access them as if each was a separate attribute. "I couldn't find ...
Examples from our training material
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
Overloading operators in Python
Background information
Some modules are available for download as a sample of our material or under an Open Training Notes License for free download from [here].
Topics covered in this module
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.
Overloading operators.
A practical example of overloading operators.
Complete learning
If you are looking for a complete course and not just a information on a single subject, visit our Listing and schedule page.

Well House Consultants specialise in training courses in Ruby, Lua, Python, Perl, PHP, and MySQL. We run Private Courses throughout the UK (and beyond for longer courses), and Public Courses 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.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2023: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/resources/Y112.html • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb