从以数字开头的模块中导入类

2024-03-29 10:49:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从一个以number开头的python文件中导入一个类(而不是整个文件)。 有一个关于导入整个模块的主题,它可以工作,但我找不到解决这个问题的方法。 (In python, how to import filename starts with a number

通常是:

from uni_class import Student

尽管文件名为123_uni_class。你知道吗

尝试了不同的

importlib.import_module("123_uni_class")

以及

uni_class=__import__("123_uni_class")

错误:

    from 123_uni_class import Student
            ^
 SyntaxError: invalid decimal literal

Tags: 模块文件to方法infromimportnumber
2条回答

对我来说很有用:

Python 3.6.8 (default, Feb 14 2019, 22:09:48)
[GCC 7.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import importlib
>>> importlib.import_module('123_a')
<module '123_a' from '/path/to/123_a.py'>
>>> __import__('123_a')
<module '123_a' from '/path/to/123_a.py'>

您不会看到包含文字文本“from 123\u uni\u class import…”的实际语法错误,除非您实际有一些包含该行的源代码。你知道吗

如果必须这样做,您还可以完全绕过导入系统,方法是读取文件的内容并^{}将它们放入您提供的名称空间中。例如:

mod = {}
with open('123_uni_class.py') as fobj:
    exec(fobj.read(), mod)

Student = mod['Student']

例如,这种通用技术用于读取用Python之类的语言编写的配置文件。不过,我不鼓励将其用于正常使用,并建议您只使用有效的模块名。你知道吗

importlib.import_module("123_uni_class")在导入模块后返回该模块,必须为其提供有效名称才能重用该模块:

import importlib

my_uni_class = importlib.import_module("123_uni_class")

然后你就可以用“我的大学”这个名字访问你的模块了。你知道吗

如果123_uni_class在这个上下文中是有效的,那么这就相当于import 123_uni_class as my_uni_class。你知道吗

相关问题 更多 >