0

I have the module Test.py with class test inside the module. Here is the code:

class test:
 SIZE = 100;
 tot = 0;
 def __init__(self, int1, int2):
 tot = int1 + int2;
 def getTot(self):
 return tot;
 def printIntegers(self):
 for i in range(0, 10):
 print(i);

Now, at the interpreter I try:

>>> import Test
>>> t = test(1, 2);

I get the following error:

Traceback (most recent call last):
 File "<pyshell#1>", line 1, in <module>
 t = test(1, 2);
NameError: name 'test' is not defined

Where did I go wrong?

Ashwini Chaudhary
252k60 gold badges479 silver badges520 bronze badges
asked Jan 14, 2013 at 21:36
1
  • Class names should start with capital letter. Commented Jan 14, 2013 at 21:58

3 Answers 3

6

You have to access the class like so:

Test.test

If you want to access the class like you tried to before, you have two options:

from Test import *

This imports everything from the module. However, it isn't recommended as there is a possibility that something from the module can overwrite a builtin without realising it.

You can also do:

from Test import test

This is much safer, because you know which names you are overwriting, assuming you are actually overwriting anything.

answered Jan 14, 2013 at 21:37
Sign up to request clarification or add additional context in comments.

1 Comment

+1, but I wouldn't say "because you know you're not overwriting anything", this isn't explicitly true. I would say "because you know which names you happen to be overwriting, assuming you are overwriting them".
1

Your question has already been answered by @larsmans and @Votatility, but I'm chiming in because nobody mentioned that you're violating Python standards with your naming convention.

Modules should be all lower case, delimited by underscores (optional), while classes should be camel-cased. So, what you should have is:

test.py:

class Test(object):
 pass

other.py

from test import Test
# or 
import test
inst = test.Test()
answered Jan 14, 2013 at 21:55

2 Comments

what is the pass keyword here?
It declares a class that inherits from object but doesn't do anything else (empty declaration). Definitely not something that should be used in practice, but good for demos such as this.
0

When you do import Test, you can access the class as Test.test. If you want to access it as test, do from Test import test.

answered Jan 14, 2013 at 21:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.