Can't import modules

Benjamin Kaplan benjamin.kaplan at case.edu
Sun Sep 30 16:15:11 EDT 2012


On Sun, Sep 30, 2012 at 12:42 PM, Peter Farrell
<peterfarrell66 at gmail.com> wrote:
> Hello!
>
> I'm still new to Python, so here's another easy one. After I save something I've done as a .py file, how do I import it into something else I work on? Every time I try to import something other than turtle or math, I get this error message:
>
> 'module' object is not callable
>
> What am I doing wrong?
>
> Thanks!
>
> Peter Farrell
> San Mateo, CA
> --

Well, you haven't told us what you're doing, so it's hard to say what
you're doing wrong. So I'm going to make a few guesses.

1. Your first (and possibly only other) language was Java.
2. You're making a class (let's say Foo) and putting it in a file of
the same name (Foo.py)
3. You're doing "import Foo" and then calling "Foo()" trying to
instantiate the class.

Python doesn't have that "one class per file, and the file must have
the same name as the class" rule as Java. The file defines a module,
which is an object and can have any number of objects (including
classes, because those are objects too) in it.

$ cat foo.py
class Foo(object):
	pass

def add2(y) :
	return y + 2
bkaplan:~ bkaplan$ python
Python 2.7.3 (default, Apr 23 2012, 10:06:17)
[GCC 4.2.1 Compatible Apple Clang 3.1 (tags/Apple/clang-318.0.58)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>> dir(foo)
['Foo', '__builtins__', '__doc__', '__file__', '__name__',
'__package__', 'add2', 'x']
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> foo.Foo()
<foo.Foo object at 0x100ad9d10>
>>> foo.add2(5)
7



More information about the Python-list mailing list