python - 从另一个 python 文件导入类错误

标签 python class import

我有三个文件.pyMain.pyone_file.pysecond_file.py。 在 one_file.py 中,我有一个名为 Create 的类。

main.py中我有这样的东西:

import one_file
var = input("yes or no?")
if var == "yes":
    Create()

但我收到此错误NameError:名称“Create”未定义。 我还尝试使用 from one_file import Createfrom 。导入one_file 但无论如何它都不起作用。

one_file.py 中的代码:


import random
class Create:
    def __init__(self):
        self.word()

    def word(self):
        word_list = ["hello", "word", "sun", "moon"]
        print("This is your word")
        print(random.choice(word_list))

最佳答案

如果您想从导入的库运行代码,您应该首先调用导入的库。

import one_file
one_file.Create()

否则,你可以尝试

from one_file import Create
Create()

关于python - 从另一个 python 文件导入类错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52364721/

相关文章:

python - 从字符串动态导入文件中的方法

python - 我无法从另一个级别的文件夹导入类

Python-如何从多索引数据框中选择行

c++ - 类的构造函数的声明和定义并打印私有(private)和公共(public)变量?

用于导入 JAR 文件的 Java 代码

python - 创建具有未知数量属性的类实例

python - 使用 numpy 数组计算函数返回 inf 和 nan

python - 如何使用Python通过使用dataFrame中的某列数据绘制正态概率图

python - 提取/附加满足涉及多列的复杂条件的 Pandas 数据框行

Python 动态导入和 __all__