【问题标题】:Import class form another python file Error从另一个 python 文件导入类错误
【发布时间】:2019-02-21 04:48:05
【问题描述】:

我有三个文件.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))

【问题讨论】:

  • from one_file import Create 应该可以工作。当你尝试时会发生什么?错误信息是什么?
  • one_file.Create() 也应该可以工作
  • 如果我尝试from one_file import Create ImportError: cannot import name Create
  • 可以你的one_file.py的邮编

标签: python class import


【解决方案1】:

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

import one_file
one_file.Create()

否则你可以试试

from one_file import Create
Create()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 2021-02-10
    • 1970-01-01
    相关资源
    最近更新 更多