[Tutor] exercise with classes

Alan Gauld alan.gauld at btinternet.com
Fri Feb 3 02:09:23 CET 2012


On 02/02/12 17:36, Tonu Mikk wrote:

> So far I have searched for info on how to pass variables from one class
> to another and have been able to create a small two class program
> (attached).   But I seem unable to generalize from here and apply this
> to the game exercise.  What would you suggest for me to try next?

Remember that OOP is about creating objects from classes.
You can pass an object to another rather than just the
variables, in fact its preferable!

Also remember that you can create many objects from one class.
So just because you have one Room class doesn't mean you are
stuck with one room object. You can have many and each can
be connected to another.

You can get rooms to describe themselves, you can enter a room.
You might even be able to create new rooms or destroy existing ones. 
These actions can all be methods of your Room class.

Here is an example somewhat like yours that passes objects:

class Printer:
    def __init__(self,number=0):
       self.value = number
    def sayIt(self):
       print self.value

class MyApp:
    def __init__(self, aPrinter = None):
        if aPrinter == None:     # if no object passed create one
           aPrinter = Printer()
        self.obj = aPrinter      # assign object
    def doIt()
        self.obj.sayIt()         # use object

def test()
    p = Printer(42)
    a1  MyApp()
    a2 = MyApp(p)   # pass p object into a2
    a1.doIt()   # prints default value = 0
    a2.doIt()   # prints 42, the value of p

test()

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list