1

I'm learning Python just so I can tinker with the files from AIMA easily. I know Java and C++, but I find the AIMA code on the repositories to be too obfuscated. The Python code looks simpler and more elegant...yet, I don't know Python.

I wanna import the functions in search.py.

I tried creating a search2.py file like this:

import search

class Problem2(Problem):
    pass

on the folder where search.py is and got:

~/aima/aima-python$ python search2.py
Traceback (most recent call last):
  File "search2.py", line 3, in <module>
    class Problem2(Problem):
NameError: name 'Problem' is not defined

Why is this?

andandandand
  • 21,946
  • 60
  • 170
  • 271
  • Probably related: http://stackoverflow.com/questions/3188929/why-import-when-you-need-to-use-the-full-name – David Z Sep 25 '11 at 23:30

3 Answers3

7

When you import search, you define the name search, as a module created from executing search.py. If in there is a class called Problem, you access it as search.Problem:

import search

class Problem2(search.Problem):
    pass

An alternative is to define Problem with this statement:

from search import Problem

which executes search.py, then defines Problem in your file as the name Problem from the newly-created search module. Note that in this form, the name search is not defined in your file.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
3

You have two options here:

  1. Instead of import search, write from search import Problem

  2. Instead of class Problem2(Problem), write class Problem2(search.Problem)

infrared
  • 3,566
  • 2
  • 25
  • 37
0

If class Problem is located in the search module, you have to import it either like that from search import Problem or use it like that:

import search

class Problem2(search.Problem):
    pass
Constantinius
  • 34,183
  • 8
  • 77
  • 85