[英]I'm getting an error “module not found ” when I'm trying to execute shell commands through a python script
[英]Python: I'm trying to import an instance from module 2 and run it through a class in module 1
我在這個網站和其他網站上嘗試過幾個“解決方案”,我一定會遺漏一些東西。 為什么圖中的代碼會出現名稱錯誤。
我試過從cars2 import *但是這並不像其他幾個那樣好。
我沒有想法。 我錯過了什么?
在定義之前,您正在調用類cars
。
您應該執行以下操作:
在文件cars1.py
:
class cars:
def __init__(self, model):
self.model = model
在文件cars2.py
:
from cars1 import cars
firstCar = cars("Honda")
print(firstCar.model)
在運行代碼時,您應該運行cars2.py
而不是cars1.py
。
因此,如果您使用保存文件cars2.py
文件的文件夾中的命令行,則應將其作為python cars2.py
運行。
您還可以通過更新它來運行代碼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.