3

in a .py file I have the following:

class avgbox:
    def __init__(self,t,n,a):
        self.t = t
        self.n = n
        self.a = a
    def add(x):
        self.t += x
        self.n += 1
        self.a = t/n

Now when I do the from file.py import * in the interactive python shell run from the ubuntu command line, it shows no error. Then when do a = avgbox(0,0,0) it says NameError: name 'avgbox' is not defined. Any ideas? What am I doing wrong here? Thanks!

5
  • Using from foo import * is nearly always a bad idea. Commented Sep 12, 2013 at 18:35
  • 1
    try from file import avgbox Commented Sep 12, 2013 at 18:35
  • 2
    you also need self as the first argument in the add method! Commented Sep 12, 2013 at 18:36
  • I think from file.py import * should be throwing an error. Try from file import *. Commented Sep 12, 2013 at 18:37
  • Most likely, you didn't restart your interactive interpreter and get a cached version of the module that doesn't yet contain the class avgbox. Try from file import avgbox, and if this doesn't work, restart your interactive interpreter. Commented Sep 12, 2013 at 18:46

2 Answers 2

2

I copy pasted your code into a file named "file.py". Then I did the following:

from file import *

avgbox(1, 2, 3)

It worked. Maybe your mistake was that you were doing from file.py import * when you should just be doing from file import * Remember that when Python searches for module names, it automatically appends .py to the name of the module if it's looking for a Python file within the current directory. Of course, you can also search within packages using the from syntax, but that's a different story.

Sign up to request clarification or add additional context in comments.

Comments

0

You must make sure that the file is in the same directory as your python interpreter is. You must also remove the .py in the from file.py import * as the .py signifies a different module in a package, for example import os.path. If the file is not in the same directory as the python shell, you must make sure that python is able to find it in your PATH variable.

It is also notable that you should not usually do a from file import * as this will pollute the namespace that you import it into, as it imports it as function_names instead of module.function_names. You can do from file import function1,function2,... and this will only import those functions into the current namespace, and no others.

Also, make sure that in a class you put self as the first parameter for each function in the class, as it will raise a syntax error if you don't.

Comments

Your Answer

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.