[Tutor] Question About Subclasses

Michael P. Reilly arcege@shore.net
Tue, 27 Feb 2001 20:06:45 -0500 (EST)


> I'm having some problems getting Python to create a subclass. I have a class 
> called Items, and then a subclass of that called Containers. Python doesn't 
> recognize Containers as a valid subclass.
> 
> This is what I have in a file called "Classes.py":
> 
> class Items:
>     def __init__(self, name, ip):
>         self.name = name
>         self.inPossesion = ip
> 
> class Containers(Items):
>     def __init__(self, name, ip, oc):
>         Items.__init__(self, name, ip)
>         self.openClosed = oc
> 
> Then within another file called "game.py" I have the following code:
> 
> import Classes
> 
> cupboard = Containers("cupboard", 0, "closed")
> 
> key = Items ("worn key", 0)
> 
> When I go to run this code, Python spits this back at me:
> 
> >>>
> Traceback (innermost last):
>   File "C:/Program Files/Python20/game.py", line 3, in ?
>     cupboard = Containers("cupboard", 0, "closed")
> NameError: There is no variable named 'Containers'
> 
> What am I doing wrong?

It is not a problem with your classes, it is how you are importing the
module.  Using the "import" statement as you are, you need to qualify
the subclass.

>>> import Classes
>>> cupboard = Classes.Containers("cupboard", 0, "closed")

If you use "from Classes import Containers", then you can use just
"Containers".

>>> from Classes import Containers
>>> cupboard = Containers("cupboard", 0, "closed")

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------