| |||||||||||
| |||||||||||
Multiple classes interacting - tap simulation example (Mk 2) in Python
this example from a Well House Consultants training course
Source code: waterflows.py Module: Y301
#!/usr/bin/env python
"""This is a test program for the following classes waterconnection defines a connection to the water mains tap defines a tap thats on a connection supertap defines a high capatcity tap on a connection change defines an action turning a tap on or off Class tap is at the "core" of the test application / suite of classes. You define a tap on a connection, and within the tap the class retains information about the tap and also its current state. Trying to turn a tap on beyond its maximum flow, or beyond the maximum flow to the connection that it's connected to, will result in it silently being limited - this maximising being hidden within (a.k.a. "encapsulated") within the class. A supertap is a varient of a tap. The only difference that we've defined is that a supertap has a maximum flow that's twice that of a regular tap, and it needs to be turned on or off twice to reach that maximum flow. Supertap uses all the logic from tap - we have NOT duplicated the logic - so it just overrides the methods where necessary. In OO terms, supertap is a class that's extended from class tap, or supertap is a subclass of tap. The change class defines an action rather than a physical thing. It's quite common in OO terms for a class of objects to be use to represent information that's a concept like this, but it's quite a hard thing for trainees to grasp sometimes. We've used the change class to let us define a piece of data that has a number (2) of different properties - whether it's an on or off action, and whether it's hot or cold, and to interpret a complex incoming piece of information (a string in this case) to work out just what the action involve is and store that action for use, perhaps many times over. The final class (waterconnection) allows us to attach different taps to different connections to the water mains, each of which has an overall capacity. Within each water connection object, we're holding a state (the current flow) and a property that we're not changing (the maximum flow) and we're accessing those properties directly - we haven't provided accessor methods since the data is only being looked at from within our own other closely associated classes. It's disputable in OO terms whether or not we should have accessed the properties this way, or provided accessor methods for each.""" class change: def __init__(self): self.summat = 0 def act_on(self,dowhat): self.temperature, self.destinedstate = dowhat.split(",") def gettap(self): return self.temperature def getdirn(self): return self.destinedstate class waterconnection: def __init__(self,name,capacity): self.name = name self.mainsmax = capacity self.mainsnow = 0 class tap: def __init__(self,room,connex): self.mktap(room,connex,1) def mktap(self,room,connex,maxflow): # A separate method so that subclasses can create # taps with different maximum flows yet share the # constructor code self.title = room self.hot = 0 self.cold = 0 self.maxflow = maxflow self.connex = connex def getname(self): return self.title def gethotflow(self): return self.hot def getcoldflow(self): return self.cold def getmaxflow(self): return self.maxflow def apply(self,doingwhat): # This is the "heavy" logic that we want encapsulated! whichtap = doingwhat.gettap() whichway = doingwhat.getdirn() maxup = self.connex.mainsmax - self.connex.mainsnow if maxup >= 1: if whichway == "on": if whichtap == "hot": if self.hot < self.maxflow: self.hot += 1 self.connex.mainsnow += 1 else: if self.cold < self.maxflow: self.cold += 1 self.connex.mainsnow += 1 else: if whichtap == "hot": if self.hot > 0: self.hot -= 1 self.connex.mainsnow -= 1 else: if self.cold > 0: self.cold -= 1 self.connex.mainsnow -= 1 def __str__(self): # redefine the method used if we convert a tap object to # a string - for example if we print it out amount1 = self.gethotflow() amount2 = self.getcoldflow() rstring = self.title + " on '" + self.connex.name + "' connection. " rstring += "Current flow is "+str(amount1)+" hot "+str(amount2)+ " cold." return rstring class supertap(tap): def __init__(self,room,connex): self.mktap(room,connex,2) # ########################################### # test program / demonstration code if __name__ == "__main__": # define a number of water connections springfield = waterconnection("403, The Spa",3); wellhouse = waterconnection("404, The Spa",5); # define a number of taps users = [] users.append(tap("utility room",wellhouse)) users.append(tap("guest bedroom",springfield)) users.append(supertap("kitchen",wellhouse)) users.append(tap("library",wellhouse)) users.append(tap("master bedroom",springfield)) users.append(tap("shower room",wellhouse)) # Define what Lisa and Leah would like to do with taps leahdoes = change() lisadoes = change() action1 = "hot,on" action2 = "cold,on" # Encapsulate the action within the "change" object because # there's going to be some complex logic to hide leahdoes.act_on(action1) lisadoes.act_on(action2) # Have leah and lisa visit each tap in turn and apply their changes for flow in users: # Better say which tap we're looking at to help the reader where = flow.getname() upto = flow.getmaxflow() print "The tap in the "+where+" has a maximum flow of "+str(upto) # Leah visits each tap twice and does her thing and the Lisa # then visits each tap once and does hers! flow.apply(leahdoes) flow.apply(leahdoes) flow.apply(lisadoes) for flow in users: print flow Learn about this subject
This module and example are covered as required on private courses.
Should you wish to cover this example and associated subjects, and you're attending a public course
to cover other topics with us, please see our extra topic program.
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 "this" training module. You'll find a description of the topic and some
other closely related examples on the "this" 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
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. |
| ||||||||||
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho PAGE: http://www.wellho.net/resources/ex.php • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb |