小编lud*_*ter的帖子

在类中使用import

我是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 …
Run Code Online (Sandbox Code Playgroud)

python import class

9
推荐指数
1
解决办法
1万
查看次数

标签 统计

class ×1

import ×1

python ×1