Hi, I am new in programing, thank for your help.
I have tried to import class form different python file located in the same folder with file i was working at, but method that I have used did not work, but is should
Main file (POOP.py)
#start of the code
from car import Car
car_1 = Car("Chevy", "Corvette", 2021, "blue")
car_2 = Car("Ford", "Mustang", 2022, "red")
print(car_1.make)
print(car_1.model)
print(car_1.year)
print(car_1.color)
car_1.drive()
#end of the code
car,py #start of the code
class Car:
def __init__(self,make,model,year,color):
self.make = make
self.model = model
self.year = year
self.color = color
def drive(self):
print("This car is driving")
def stop(self):
print("This car is stopped")
#end of the code
this is the error: AttributeError: ‘Car’ object has no attribute ‘drive’
Could you please help me.
Thank you.
Please fix the formatting so that we can read the code.
Make sure all the code in inside the ``` marks.
I think you have a problem with how you have indented the code.
The Car class should look like this.
class Car:
def init(self, make, model, year, color):
self.make = make
self.model = model
self.year = year
self.color = color
def drive(self):
print("This car is driving")
def stop(self):
print("This car is stopped")
Given the code that you have so far, I don’t see any issues.
When I run this…
from car import Car
car_1 = Car("Chevy", "Corvette", 2021, "blue")
car_2 = Car("Ford", "Mustang", 2022, "red")
print(car_1.make)
car_1.drive()
print(car_2.make)
car_2.stop()
… I get this output:
Chevy
This car is driving
Ford
This car is stopped
Things to check: make sure you are in fact, using the correct car.py file. I’ll also delete any __pycache__ directory, but that aside, I can’t see why you’d still not get the same output that I’m seeing.
Whenever i try to run the code it fails and in the folder appear pycache with text file called “car.cpython-311” , maybe it has something relevant to this error. After each attempt i delete this folder and it appears each time i run the code. I have checked i have only one file car.py
Yes. The __pycache__ directory will get recreated, because that’s how it works: I suggested you delete it, just so that it would get recreated on the next code run and thus not be an old version that was created when the script failed.
I don’t know why you’re still getting problems, if your code is identical to what you have posted here: all I’ve done, is to simply C&P it.
You have both files in the same directory tree location, yes?
What trace back error are you seeing?
Yeah I have both files in the same direcrotry, I even recreated the directory,this is the error AttributeError: 'Car' object has no attribute 'drive' I will try to crate new one with new files and copy paste the code