python import results in nameerror

梦想的初衷 提交于 2021-01-29 08:53:05

问题


This seems pretty basic, so I must be missing something obvious. Goal is to import a module from the same directory. I've broken it down about as simple as I can and I'm getting the nameerror.

file import_this.py:

def my_function(number) :
    print number + 2

file import_test.py:

import import_this
my_function(2)

Do I have to specify the directory the import file is in? (It's in the same as the test file). Also, can I test to see what modules are imported?


回答1:


You are accessing the function incorrectly.

Either use the following

import import_this
import_this.my_function(2)

or do,

from import_this import my_function
my_function(2) 



回答2:


Alternatively (apart from @mu's answer above),

>>>import import_this as it

.. and then,

>>> it.my_function(2) 


来源:https://stackoverflow.com/questions/24783954/python-import-results-in-nameerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!