using import inside 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
@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)
而不加前缀self
或Test
。
zeit
这样的非英语标识。只会说英语的人应该能够阅读您的代码。
这篇关于在类内使用导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:在类内使用导入


猜你喜欢
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01