lud*_*ter 9 python import class
我是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
Run Code Online (Sandbox Code Playgroud)
@wombatz得到了正确的提示:它必须是self.zeit.sleep(2)或Test.zeit.sleep(2).导入也可以在类声明之上完成.
Test.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)
Run Code Online (Sandbox Code Playgroud)
和
run.py
from test import Test
foo = Test()
foo.doit()
Run Code Online (Sandbox Code Playgroud)
当我尝试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
Run Code Online (Sandbox Code Playgroud)
我从错误中理解的是,类中的导入无法识别.但是,如何才能认识到班级中的导入是否被认可?
Wom*_*atz 11
必须从该类访问类的名称空间内定义的所有内容.这适用于方法,变量,嵌套类以及包括模块在内的所有其他内容.
如果您确实要在类中导入模块,则必须从该类访问它:
class Test:
import time as zeit
def timer(self):
self.zeit.sleep(2)
# or Test.zeit.sleep(2)
Run Code Online (Sandbox Code Playgroud)
但是为什么要在课程中导入模块呢?我想不出它的用例,尽管它希望它放入该命名空间.
你真的应该将导入移动到模块的顶部.然后你可以zeit.sleep(2)
在课堂内调用,而不需要前缀self
或Test
.
你也不应该使用非英语标识符zeit
.只会说英语的人应该能够阅读你的代码.
归档时间: |
|
查看次数: |
11182 次 |
最近记录: |