import file but reports error NameError: name 'something' is not defined

不羁的心 提交于 2021-02-05 11:13:24

问题


testa.py

class A:

    s1 = 333
    __age = 0

    def __init__(self,age ):
        self.__age=age
        return

    def __del__(self):  

        return  
    #private
    def __doSomething(self, s): 
        print self.__age 
        return            
    #public
    def doSomething(self, s):  
        self.__doSomething(s)    
        print s

test.py

import sys
import testa

a=A(111)
a.doSomething('222')

run

python test.py

it reports error:

NameError: name 'A' is not defined

your comment welcome


回答1:


Use
a=testa.A(111)

You must name the package unless you import A explicitly e.g

from testa import A




回答2:


Remember this:

Doing: import mymodule does not import the whole methods and attributes of mymodule to the namespace, so you will need to refer to mymodule, everytime you need a method or attribute from it, using the . notation, example:

x = mymodule.mymethod()

However, if you use:

from mymodule import * 

This will bring every method and attribute of mymodule into the namespace and they are available directly, so you don't need to refer to mymodule each time you need to call one of its method or attribute, example:

from mymodule import *

x = mymethod()  #mymethod being a method from mymodule

You can also import specific method if you don't want to bring the whole module:

from mymodule import myMethod

For further details, read the Python docs:

https://docs.python.org/2/tutorial/modules.html



来源:https://stackoverflow.com/questions/30149154/import-file-but-reports-error-nameerror-name-something-is-not-defined

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