简体   繁体   English

Python:我正在尝试从模块2导入一个实例,并通过模块1中的类运行它

[英]Python: I'm trying to import an instance from module 2 and run it through a class in module 1

I have tried several "solutions" on this site and other and I must be missing something. 我在这个网站和其他网站上尝试过几个“解决方案”,我一定会遗漏一些东西。 Why does the code pictured give a name error. 为什么图中的代码会出现名称错误。

I've tried from cars2 import * but that didn't work as well as a few others. 我试过从cars2 import *但是这并不像其他几个那样好。

I'm out of ideas. 我没有想法。 What am I missing? 我错过了什么?

https://i.stack.imgur.com/EHuay.jpg https://i.stack.imgur.com/EHuay.jpg

You are calling the class cars before defining it. 在定义之前,您正在调用类cars

You should do the following: 您应该执行以下操作:

In the file cars1.py : 在文件cars1.py

class cars:
    def __init__(self, model):
        self.model = model

In the file cars2.py : 在文件cars2.py

from cars1 import cars
firstCar = cars("Honda")

print(firstCar.model)

And while running the code, you should run cars2.py and not cars1.py . 在运行代码时,您应该运行cars2.py而不是cars1.py

So you should run it as python cars2.py if you are using command line from the folder in which the file cars2.py file is saved in. 因此,如果您使用保存文件cars2.py文件的文件夹中的命令行,则应将其作为python cars2.py运行。

You can also do run the code cars1.py by updating it as follows: 您还可以通过更新它来运行代码cars1.py ,如下所示:

class cars:
    def __init__(self, model):
        self.model = model

if __name__=="__main__":
    from cars2 import firstCar
    print(firstCar.model)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM