在类内使用导入 [英] using import inside class

查看:27
本文介绍了在类内使用导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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


@OMAMBATZ得到了正确的提示: 它必须是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.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

我从错误中理解的是,类中的导入无法识别。但我如何才能使课堂上的重要性得到认可呢?

推荐答案

类的命名空间中定义的所有内容都必须从该类访问。这适用于方法、变量、嵌套类以及包括模块在内的所有其他对象。

如果您确实要在类中导入模块,则必须从该类访问它:

class Test:
    import time as zeit
    def timer(self):
        self.zeit.sleep(2)
        # or Test.zeit.sleep(2)

但是为什么要在类中导入模块呢?我想不出这方面的用例,尽管我希望将其放入该命名空间。

您确实应该将导入移到模块的顶部。然后,您可以在类内调用zeit.sleep(2)而不加前缀selfTest

此外,您不应该使用zeit这样的非英语标识。只会说英语的人应该能够阅读您的代码。

这篇关于在类内使用导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆