[Tutor] exercise with classes

Tonu Mikk tmikk at umn.edu
Mon Feb 6 17:12:25 CET 2012


Alan, thanks for explaining about passing objects to classes.  This is an
important concept for me to understand.

I tried running the code, but run into an error that I could not resolve:

TypeError: doIt() takes no arguments (1 given).

Tonu

On Thu, Feb 2, 2012 at 7:09 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> 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/
>
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
Tonu Mikk
Disability Services, Office for Equity and Diversity
612 625-3307
tmikk at umn.edu
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120206/85db66b3/attachment.html>


More information about the Tutor mailing list