[Tutor] Tutor Digest, Vol 33, Issue 52

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Nov 13 16:27:48 CET 2006


> Is it possible to a single that contains two classes:
>
> Myclass.py file contains:
>
> Class one(object):
>  def needsomething(self):
> Class two (object):
>   def dosomething(self):
>
> I want Class one's methods to access Class two methods?
>
> Class one(object):
>  def needsomething(self):
>    return dosomething()


An instance of class one can talk to an instance of class two, if that's 
what you're trying to do.

#####################################################
class Mailbox:
     def __init__(self):
         self.messages = []

     def accept_message(self, msg):
         print 'I see a new message', msg.title
         self.messages.append(msg)

class Message:
     def __init__(self, title, contents):
         self.title, self.contents = title, contents

     def insert_into_mailbox(self, mbox):
         mbox.accept_message(self)
#####################################################


Given this, we can make a Mailbox and put a bunch of Messages into it.

###############################################################
>>> my_mailbox = Mailbox()
>>> message_1 = Message("hello world", "this is a test")
>>> message_2 = Message("goodbye world", "thanks for watching")
>>>
>>> message_1.insert_into_mailbox(my_mailbox)
I see a new message hello world
>>> message_2.insert_into_mailbox(my_mailbox)
I see a new message goodbye world
###############################################################


Note that Message.insert_into_mailbox() is expecting to talk to a Mailbox.


More information about the Tutor mailing list