从另一个Python文件导入类错误

时间:2018-09-17 09:35:43

标签: 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: name 'Create' is not defined。 我还尝试了from one_file import Createfrom . import 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))

1 个答案:

答案 0 :(得分:2)

如果要从导入的库中运行代码,则应首先调用导入的库。

import one_file
one_file.Create()

否则,您可以尝试

from one_file import Create
Create()
相关问题