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.
I'm out of ideas. What am I missing?
You are calling the class cars
before defining it.
You should do the following:
In the file cars1.py
:
class cars:
def __init__(self, model):
self.model = model
In the file 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
.
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.
You can also do run the code cars1.py
by updating it as follows:
class cars:
def __init__(self, model):
self.model = model
if __name__=="__main__":
from cars2 import firstCar
print(firstCar.model)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.