Vivek Gautam
Vivek Gautam

Reputation: 25

AttributeError: type object 'Car' has no attribute 'speed'

i got the error message when i am calling Car class with object car

class Car:
def __init__(self, speed, unit):
    self.speed = speed
    self.unit = unit
def __new__(self, speed, unit):
    str = "Car with the maximum speed of {} {}".format(self.speed, self.unit)
    return str

Upvotes: 1

Views: 711

Answers (3)

Anurag Srivastava
Anurag Srivastava

Reputation: 160

You are using __new__ and i can't tell why. You can use this instead:

class Car:
    def __init__(self, speed, unit):
        self.speed = speed
        self.unit = unit
    def new(self):
        str = "Car with the maximum speed of {} {}".format(self.speed, self.unit)
        return str

Upvotes: 0

DirtyBit
DirtyBit

Reputation: 16782

Fixing the indentation and using a method speed_check() along with a single constructor:

class Car:
    def __init__(self, speed, unit):
        self.speed = speed
        self.unit = unit
    def speed_check(self):
        return "Car with the maximum speed of {} and the unit {}".format(self.speed, self.unit)
        
CarObj = Car(120, 10)
result = CarObj.speed_check()

print(result)

OUTPUT:

Car with the maximum speed of 120 and the unit 10   

Upvotes: 0

Kuldeep Singh Sidhu
Kuldeep Singh Sidhu

Reputation: 3856

new is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class.

In contrast, init doesn't return anything; it's only responsible for initializing the instance after it's been created.

class Car:
    # def __init__(self, speed, unit):
    #     self.speed = speed
    #     self.unit = unit
    def __new__(self, speed, unit):
        self.speed = speed
        self.unit = unit
        str = "Car with the maximum speed of {} {}".format(self.speed, self.unit)
        return str

a = Car(10, 2)
print(a)
Car with the maximum speed of 10 2

In general, you shouldn't need to override new unless you're subclassing an immutable type like str, int, unicode or tuple.

ANOTHER WAY

class Car:
    def __init__(self, speed, unit):
        self.speed = speed
        self.unit = unit
    def __str__(self):
        str = "Car with the maximum speed of {} {}".format(self.speed, self.unit)
        return str

a = Car(10, 2)
print(a)
Car with the maximum speed of 10 2

Upvotes: 2

Related Questions