class relationship question
Graham Fawcett
graham__fawcett at hotmail.com
Wed Mar 5 01:18:17 EST 2003
johnwadeunderwood at yahoo.com (John Underwood) wrote in message news:<f004e9c2.0303041309.3858c2e1 at posting.google.com>...
> I have two different .py files that are as basic as "hello world"
> applications
> and a additonal file that is just a class... as simple as holding
> the value to display to the world
>
> I want them to share a class relationship, so they can pass
> information
> to each other, I'm not sure how to tackle this yet and would
> appreciate
> any help... for example..
>
Hello John,
If I'm understanding you correctly, you want to have two classes, each
defined
in a separate .py file. And you want to be able to have instances of
those two classes interact with one another.
One thing that you should be clear on is that the things you'll want
to "update" in your program will most likely be *objects* and not
*classes*. A class is a description of a number of like-minded
objects, and those objects are refered to as *instances* of their
class. Generally speaking, classes are defined before you run your
program (by you, in your source code), and objects are created and
manipulated during the run of your program (by the Python
interpreter).
Let's continue to use your "hello world" example, and define two
classes, one for data storage, the other for input and for outputting
the results.
somefile2.py
============
class Container:
"""A class of objects in which a simple value may be stored."""
def __init__(self):
self.value = None
somefile1.py
============
from somefile2 import Container
class InputOutput:
"""A class of objects that accept and store an input for later
printing."""
def __init__(self):
# create a new, but empty, instance of Container class
self.storage = Container()
def input(self):
what_to_say = raw_input("what do you want me to say? ")
self.storage.value = what_to_say
def output(self):
print 'You asked me to say "%s".' % self.storage.value
# our definitions are done, let's run some test code.
if __name__ == '__main__':
# create an instance of the InputOutput class
io = InputOutput()
# ask for input
io.input()
# spit it out
io.output()
You "import" the Container class definition from somefile2 into
somefile1 using an "import" statement at the top of somefile1. In
creating an InputOutput object, a Container object is also created,
and stored inside the first object as one of its attributes.
This does, as you asked, express a relationship between two classes:
somefile1.InputOutput is dependent upon somefile2.Container for its
functioning.
Hope this helps,
-- Graham
More information about the Python-list
mailing list