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

Recommended Answers

All 4 Replies

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]

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?

put from classA import classA in classB.py instead of import classA

That seems to fix the problem.

Thanks for the quick reply.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.