Warm tip: This article is reproduced from serverfault.com, please click

Python

发布于 2020-11-29 06:28:27

Noob Question I am needing to split the following into two different .py files and have the second file import the first file for its info.

The problem I am having trouble understanding is that when I am running the entire thing as one file, it works fine. So shouldnt it work find if I just split it and import the class from one to the next?

The error I am getting when running test.py is NameError: name 'Car' is not defined. on line mycar = Car(year, make, model)

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

#This file is named car.py

class Car: def init(self, year, make, speed):

    self.__year_model = year
    self.__make = make
    self.__speed = 0

def set_year_model(self, year):
    self.__year_model = year

def set_make(self, make):
    self.__make = make

def set_speed(self, speed):
    self.__speed = 0

def get_year_model(self):
    return self.__year_model

def get_make(self):
    return self.__make

def get_speed(self):
    return self.__speed

#methods
def accelerate(self):
    self.__speed +=5

def brake(self):
    self.__speed -=5

def get_speed(self):
    return self.__speed

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

#this file is named test.py

import car

def main():

year = input('Enter the car year: ')
make = input('Enter the car make: ')
speed = 0

mycar = Car(year, make, speed)

#Accelerate 5 times
mycar.accelerate()
print('The current speed is: ', mycar.get_speed())
mycar.accelerate()
print('The current speed is: ', mycar.get_speed())
mycar.accelerate()
print('The current speed is: ', mycar.get_speed())
mycar.accelerate()
print('The current speed is: ', mycar.get_speed())
mycar.accelerate()
print('The current speed is: ', mycar.get_speed()) 

#Brake 5 times
mycar.brake()
print('The current speed after brake is: ', mycar.get_speed())
mycar.brake()
print('The current speed after brake is: ', mycar.get_speed())
mycar.brake()
print('The current speed after brake is: ', mycar.get_speed())
mycar.brake() 
print('The current speed after brake is: ', mycar.get_speed())
mycar.brake()
print('The current speed after brake is: ', mycar.get_speed())

#Call the main function

main()

Questioner
Dustin Keith
Viewed
0
Meny Issakov 2020-11-29 14:35:33

Currently, you're importing the module named car (which is the file name). so you need to alter your code to use car.Car(...)

or the more common option, change your import statement to: from car import Car