Python类导入问题:拆分文件后运行报NameError错误
Hey there! Let's fix your issues step by step. You're getting the NameError because when you import the car module, the Car class lives inside that module's namespace—you can't reference it directly as Car unless you import it specifically. Plus, there are a couple of bugs in your original Car class that would cause functionality issues even after fixing the import.
1. Fix the Import Issue
In your test.py, you have two simple ways to access the Car class:
Option 1: Use the module namespace
Keep your original import car statement, but reference the class through the module when creating an instance:
mycar = car.Car(year, make, speed)
Option 2: Import the Car class directly
Update your import statement to pull the Car class into the current namespace explicitly:
from car import Car
This lets you keep using Car(year, make, speed) exactly as you originally wrote.
2. Fix Critical Bugs in the Car Class
Your original Car class has a few issues that would break functionality even after fixing the import:
- Constructor name error: Python's required constructor is
__init__(two underscores on each side), notinit. Your currentinitmethod won't run when creating aCarinstance, so none of your instance variables will be set correctly. - Wasted constructor parameter: You accept a
speedparameter but immediately overwrite it to0—either use the parameter or set a default value. - Broken
set_speedmethod: Right now it always sets speed to0regardless of input; it should assign the passed value instead. - Duplicate
get_speedmethod: You have two identical copies of this method—remove one. - Brake logic flaw: Braking could lead to negative speed without a check.
Here's the corrected car.py:
class Car: # Fixed constructor with optional speed default def __init__(self, year, make, speed=0): self.__year_model = year self.__make = make self.__speed = speed def set_year_model(self, year): self.__year_model = year def set_make(self, make): self.__make = make # Fixed set_speed with basic validation def set_speed(self, speed): if speed >= 0: self.__speed = speed def get_year_model(self): return self.__year_model def get_make(self): return self.__make def get_speed(self): return self.__speed def accelerate(self): self.__speed += 5 # Fixed brake to prevent negative speed def brake(self): self.__speed = max(self.__speed - 5, 0)
3. Updated test.py (using Option 2 import)
I also replaced repetitive accelerate/brake calls with loops to clean up the code—this is optional but makes the code more concise:
from car 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 for _ in range(5): mycar.accelerate() print('The current speed is: ', mycar.get_speed()) # Brake 5 times for _ in range(5): mycar.brake() print('The current speed after brake is: ', mycar.get_speed()) main()
内容的提问来源于stack exchange,提问作者Dustin Keith

