Training, Open Source Programming Languages

This is page http://www.wellho.net/resources/ex.php4

Our email: info@wellho.net • Phone: 01144 1225 708225

 
For 2023 (and 2024 ...) - 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))
inheritance, factory, decorator, comparators, static methods, caching, etc
Code testing, patterns, profiles and optimisation. example from a Well House Consultants training course
More on Code testing, patterns, profiles and optimisation. [link]

This example is described in the following article(s):
   • A demonstration of how many Python facilities work together - [link]
   • Passing optional and named parameters to python methods - [link]

Source code: travel.py Module: Y212
#!/usr/bin/env python

# inheritance, factory, decorator, comparators, static methods
# import, exceptions, stderr, sys, object state caching

import sys

# An example from some more advanced object training ...

covercount = {}

def coverage(why):

        # define how to wrap the function call
        myname = why.func_name

        def wrapped(*args, **kwargs):

                # Do the original stuff (of course?)
                finalanswer = why(*args, **kwargs)

                # Extra bits to be performed ...
                sofar = covercount.get(myname,0)
                covercount[myname] = sofar + 1

                return finalanswer

        # pass back the wrapped function
        # and pass back the wrapped docstring too
        wrapped.__doc__ = why.__doc__
        return wrapped

def coverage_report():
        print "\nHow many times each method was called:"
        for func in covercount.keys():
                print covercount[func],func

class travel(object):
        @coverage
        def __init__(self,defstring):
                type, self.leaves, self.destiny, \
                self.carpacity, self.duration = defstring.split('\t')
                self.cars = 1
                self.cached = False
                self.regulator = "Maritime agency"

        def getdest(self):
                return self.destiny
        getdest = coverage(getdest)

        @coverage
        def getcars(self):
                return int(self.cars)

        @coverage
        def getadmins(self):
                return self.getpeeps() * int(self.duration)

        @coverage
        def more_opportunities(this,that):
                val = cmp(this.getadmins(), that.getadmins())
                if (val > 0): return this
                return that

        @staticmethod
        @coverage
        def most_opportunities(possibilities):
                try:
                        so_far = possibilities[0]
                except:
                        raise
                for maybe in range(1,len(possibilities)):
                        so_far = so_far.more_opportunities(possibilities[maybe])
                return so_far

        @staticmethod
        @coverage
        def factory(line):
                have = None
                if line.startswith("train\t"):
                        have =train(line)
                elif line.startswith("bus\t"):
                        have = bus(line)
                elif line.startswith("floating bridge\t"):
                        have = ferry(line)
                if not have:
                        # exits function on "raise", no value returned
                        # raise creates an exception object
                        raise TypeError, "Not a valid travel mode"
                return have

        @coverage
        def getpeeps(self):
                if not self.cached:
                        self.peeps = int(self.carpacity) * int(self.cars)
                        self.cached = True
                return self.peeps

        @coverage
        def __str__(self):
                itsa = self.__class__.__name__
                passes = self.getpeeps()
                return "A " + "%-8s" % itsa + " with space for " + \
                        "%4d" % passes

        # set up an attribute called "people".
        # use the getpeeps method to read, and None to write
        people = property(getpeeps,None)

class train (travel):

        @coverage
        def __init__(self,defstring):
                type, self.leaves, self.destiny, self.cars, \
                self.carpacity, self.duration = defstring.split('\t')
                self.cached = False
                self.regulator = "ORR"

class roadie (travel):
        pass

class bus (roadie):

        @coverage
        def __init__(self,defstring):
                # travel.__init__(self, defstring)
                # Above is deprecated - use the following:
                super(bus,self).__init__(defstring)
                self.regulator = "DfT"

        @coverage
        def getpeeps(self):
                if not self.cached:
                        self.peeps = int(self.carpacity) - 1
                        self.cached = True
                return self.peeps

class ferry(travel):
        pass

# ---------------------------------------------------------

if __name__ == "__main__":
        params = sys.argv
        if len(params) < 2:
                fh = sys.stdin
        else:
                try:
                        fh = open(sys.argv[1])
                except IOError, e:
                        sys.stderr.write("Error 1543: Can't open "+sys.argv[1]+" for read: ")
                        sys.stderr.write(e.strerror + "\n")
                        # Do not recussitate ;-)
                        sys.exit(1)
                except StandardError, e:
                        sys.stderr.write("Error 1544: Dallas, we have an unusual problem\n")
                        sys.stderr.write("And it's a "+ e.__class__.__name__ + "\n")
                        sys.exit(1)
        options = []
        for line in fh:
                try:
                        options.append(travel.factory(line))
                except:
                        pass

        summery = "\n"

        for option in options:
                if option.getpeeps() < 50: continue

                # strong suggestion - hide the formatting in the class

                print "%2d" % (option.getcars()), \
                        "%-15s" % option.getdest(), \
                        "%3d" % option.getpeeps()
                print "%2d - %15s - %10s - %3d - %3d" % (option.getcars(), \
                        option.getdest(), \
                        option.regulator, \
                        option.people, \
                        option.getpeeps())

                summery += str(option) + "\n"
                # print option

        print summery

# Comparators

        try:

                first = options[3]
                second = options[5]

                print first
                print second

                print first.getadmins()
                print second.getadmins()

                sellon = first.more_opportunities(second)
                print sellon

        except:
                sys.stderr.write("Error 5544: you are short of data for comparators\n")

        try:
                sellon = travel.most_opportunities(options)
                print sellon
        except:
                sys.stderr.write('Error 5432: not even enough data for "most" test!!\n')

# Look at use of code

        coverage_report()

""" --------------------------------------------------------------

Sample data file:

train 07:17 Swindon 2 72 25
train 06:40 Southampton 2 71 89
train 19:11 Southampton 1 71 97
train 19:47 Cheltenham Spa 3 75 65
floating bridge 22:30 Hoek van Holland 1200 480
bus 07:24 Chippenham 62 24
bus 08:04 Bath 41 37
bus 08:07 Bath 61 35
floating bridge 09:20 Amsterdam 400 5
elephant 10:40 Atworth 5 45

------------------------------------------------------------------

Runs like this:

munchkin:ps grahamellis$ ./travel.py journey.txt
 2 Swindon 144
 2 - Swindon - ORR - 144 - 144
 2 Southampton 142
 2 - Southampton - ORR - 142 - 142
 1 Southampton 71
 1 - Southampton - ORR - 71 - 71
 3 Cheltenham Spa 225
 3 - Cheltenham Spa - ORR - 225 - 225
 1 Hoek van Holland 1200
 1 - Hoek van Holland - Maritime agency - 1200 - 1200
 1 Chippenham 61
 1 - Chippenham - DfT - 61 - 61
 1 Bath 60
 1 - Bath - DfT - 60 - 60
 1 Amsterdam 400
 1 - Amsterdam - Maritime agency - 400 - 400

A train with space for 144
A train with space for 142
A train with space for 71
A train with space for 225
A ferry with space for 1200
A bus with space for 61
A bus with space for 60
A ferry with space for 400

A train with space for 225
A bus with space for 61
14625
1464
A train with space for 225
A ferry with space for 1200

How many times each method was called:
12 __str__
9 factory
65 getpeeps
1 most_opportunities
9 more_opportunities
16 getcars
20 getadmins
12 __init__
16 getdest
munchkin:ps grahamellis$

----------- Another sample --------------

munchkin:ps grahamellis$ ./travel.py
^D

Error 5544: you are short of data for comparators
Error 5432: not even enough data for "most" test!!

How many times each method was called:
munchkin:ps grahamellis$

"""

Learn about this subject
This module and example are covered on the following public courses:
 * Learning to program in Python
 * Python Programming
Also available on on site courses for larger groups

Books covering this topic
Yes. We have over 700 books in our library. Books covering Python are listed here and when you've selected a relevant book we'll link you on to Amazon to order.

Other Examples
This example comes from our "Code testing, patterns, profiles and optimisation." training module. You'll find a description of the topic and some other closely related examples on the "Code testing, patterns, profiles and optimisation." module index page.

Full description of the source code
You can learn more about this example on the training courses listed on this page, on which you'll be given a full set of training notes.

Many other training modules are available for download (for limited use) from our download centre under an Open Training Notes License.

Other resources
• Our Solutions centre provides a number of longer technical articles.
• Our Opentalk forum archive provides a question and answer centre.
The Horse's mouth provides a daily tip or thought.
• Further resources are available via the resources centre.
• All of these resources can be searched through through our search engine
• And there's a global index here.

Web site author
This web site is written and maintained by Well House Consultants.

Purpose of this website
This is a sample program, class demonstration or answer from a training course. It's main purpose is to provide an after-course service to customers who have attended our public private or on site courses, but the examples are made generally available under conditions described below.

Conditions of use
Past attendees on our training courses are welcome to use individual examples in the course of their programming, but must check the examples they use to ensure that they are suitable for their job. Remember that some of our examples show you how not to do things - check in your notes. Well House Consultants take no responsibility for the suitability of these example programs to customer's needs.

This program is copyright Well House Consultants Ltd. You are forbidden from using it for running your own training courses without our prior written permission. See our page on courseware provision for more details.

Any of our images within this code may NOT be reused on a public URL without our prior permission. For Bona Fide personal use, we will often grant you permission provided that you provide a link back. Commercial use on a website will incur a license fee for each image used - details on request.

© WELL HOUSE CONSULTANTS LTD., 2024: 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/ex.php4 • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb