我对python类的概念完全不熟悉。在寻找解决方案几天后,我希望能在这里得到帮助:
我想要一个python类,在这里我导入一个函数并在那里使用它。主代码应该能够从类调用函数。为此,我有两个文件在同一个文件夹。
多亏了@cdarke,@DeepSpace和@MosesKoledoye,我编辑了这个错误,但遗憾的是没有。
我还是有错误:
test 0
Traceback (most recent call last):
File "run.py", line 3, in <module>
foo.doit()
File "/Users/ls/Documents/Entwicklung/RaspberryPi/test/test.py", line 8, in doit
self.timer(5)
File "/Users/ls/Documents/Entwicklung/RaspberryPi/test/test.py", line 6, in timer
zeit.sleep(2)
NameError: global name 'zeit' is not defined
@wombatz得到了正确的提示: 它必须是self.zeit.sleep(2)或Test.zeit.sleep(2)。导入也可以在类声明之上完成。
测试.Py
class Test:
import time as zeit
def timer(self, count):
for i in range(count):
print("test "+str(i))
self.zeit.sleep(2) <-- self is importent, otherwise, move the import above the class declaration
def doit(self):
self.timer(5)
以及
运行.py
from test import Test
foo = Test()
foo.doit()
当我试图python run.py
时,会出现以下错误:
test 0
Traceback (most recent call last):
File "run.py", line 3, in <module>
foo.doit()
File "/Users/ls/Documents/Entwicklung/RaspberryPi/test/test.py", line 8, in doit
self.timer(5)
File "/Users/ls/Documents/Entwicklung/RaspberryPi/test/test.py", line 6, in timer
sleep(2)
NameError: global name 'sleep' is not defined
我从错误中了解到的是类中的导入无法识别。但是我怎样才能使类中的导入被识别呢?
sleep
不是python内置的,并且名称本身不引用任何对象。所以Python正确地提出了一个NameEror
。你打算:
然后将
import time as zeit
移到模块的顶部。别名为
time
的zeit
模块可能没有出现在模块的全局符号表中,因为它是在class
中导入的。你想要time.sleep。你也可以使用
编辑:导入类范围内的问题已解释here。
类的命名空间中定义的所有内容都必须从该类访问。它适用于方法、变量、嵌套类以及包括模块在内的所有内容。
如果确实要在类中导入模块,则必须从该类访问该模块:
但是为什么还要在类中导入模块呢?尽管我不想让它放在那个名称空间中,但我还是想不出它的用例。
您真的应该将导入移到模块的顶部。然后可以在类内调用
zeit.sleep(2)
,而不必在self
或Test
前面加前缀。此外,不应使用非英语标识符,如
zeit
。只会说英语的人应该能读懂你的代码。相关问题 更多 >
编程相关推荐