a simple question about class composition
David Schonberger
schond at eecs.ku.edu
Wed Nov 27 20:08:42 EST 2002
I have the following two class definitions in a file called myclass.py:
###begin###
class MyClass:
def __init__(self, txt):
self.text = txt
def printText(self):
print "Text for MyClass " + str(self.text) + "\n"
class MyOtherClass:
def __init__(self,txt):
self.text = txt
def printText2(self):
print "Twice the text for MyOtherClass " + str(2*self.text) + "\n"
###end###
I then have the following code in a file called mycontainerclass.py:
###begin###
from myclass import *
class MyContainerClass:
def __init__(self, txt):
self.text = txt
self.one = MyClass(" I like Vanilla Coke")
self.two = MyOtherClass("I like Classic Coke")
def printContainerText(self):
print "Container class text " + str(self.text) + "\n"
def invokePrint(self):
self.one.printText()
self.two.printText2()
if __name__ == "__main__":
myobj = MyContainerClass("I like both Vanilla Coke and Classic Coke")
myobj.invokePrint()
myobj.printContainerText()
###end###
When I try to run this code for MyContainerClass I get the following
error:
###begin###
Traceback (most recent call last):
File "C:/Python22/mycontainerclass.py", line 18, in ?
myobj = MyContainerClass("I like both Vanilla Coke and Classic Coke")
File "C:/Python22/mycontainerclass.py", line 7, in __init__
self.two = MyOtherClass("I like Classic Coke")
NameError: global name 'MyOtherClass' is not defined
###end###
Any idea what is happening? I came across similar code in Lutz's "Learning
Python" (a good three years old; perhaps this is part of the problem). I
am running Python 2.2.1 on Win2K but have run into the same problem on
Linux. Note that if I comment out the stuff about MyOtherClass in
MyContainerClass--i.e. the stuff having to do with self.two--everything
works fine, with MyClass successfully embeded in MyContainerClass. Any
help would be appreciated. Thanks.
Regards,
David
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
* David Schonberger *
* Department of Electrical Engineering and Computer Science *
* University of Kansas *
* email: schond at eecs.ukans.edu *
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
More information about the Python-list
mailing list