0

How do I use classes in python? Do I import them?

For example:

class classA:
def __init__(self):
print "class A"

class classB:
def __init__(self):
classA_list = []
for i in range(5):
classA_list.append(classA()) #list of classA objects

This works if I have both classes in one file. But if the classes are saved in two different files, classA as classA.py and classB as classB.py, I get an error shown below. How can I fix this?

>>> classB()
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
classB()
File "C:\ClassB.py", line 19, in __init__
classA_list.append(classA())
NameError: global name 'classA' is not defined

Thanks

3
Contributors
4
Replies
6
Views
8 Years
Discussion Span
Last Post by nuaris
0

If those classes are in the file myfile.py the easiest thing to do is:

from myfile import ClassA
from myfile import ClassB
# OR, simpler:
from myfile import *

If the files are named after the class, are set up correctly, and in the same directory as the file calling them, you can simply do:

import classA, classB

And P.S. in the future: please use code tags when posting code in this forum, it makes it easier for us to read your code. use the tags as following:
[code=python] # Code in here

[/code]

0

I tried importing it, but I get an error saying module object is not callable. These are the files:

class classA:
#saved as classA.py
   def __init__(self):
      print "class A"
import classA

class classB:
#saved as classB.py
   def __init__(self):
      classA_list = []
      for i in range(5):
         classA_list.append(classA())
>>> classB()
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    classB()
  File "C:\classB.py", line 22, in __init__
    classA_list.append(classA())
TypeError: 'module' object is not callable

It works when I have both classes in the same file, but when they are separated, the error appears. Is there something more that must be done besides import?

0

That seems to fix the problem.

Thanks for the quick reply.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.