Whats the point of self.wheels = wheels


the title is just an example, but my point is why is this nessasary? "wheels" isnt used anywhere so why is this so nessasary? here is where i got the code from:

class Car(object):
    def __init__(self, wheels, miles, make, model, year, sold_on):
        """Return a new Car object."""
        self.wheels = wheels
        self.miles = miles
        self.make = make
        self.model = model
        self.year = year
        self.sold_on = sold_on

    def sale_price(self):
        """Return the sale price for this car as a float amount."""
        if self.sold_on is not None:
            return 0.0  # Already sold
        return 5000.0 * self.wheels

what i want to highlight is the sale_price function and it's last line, if we set self.wheels to be wheels, why cant we use wheels then instead. And if this cannot be done, why bother setting self.wheels to anything anyway.


It sets an attribute to the object you create. For example, you could have iron rimmed wheels, or steel rimmed wheels, it is to create variation. wheels is just an input to assign that value. You must use self.wheels or it is meaningless to the unique car.


Thank you for the prompt reply. i understand the need the for the self.wheels as its refering to an instance(variation) of the wheel. But could you eleaborate on the "=wheel" part. I still dont get that :frowning: but thx anyway


The function _ _init__ is constructor. When you are creating instance of Car class you are using this function.

In this case wheels is parameter of init function. With this parameter we set the property wheels (self.wheels) to the value of wheels.


myCar = Car(4, 1000, "Audi", "A5", 2010, None)
print myCar.wheels #4
print myCar.sale_price() #20000

yourCar = Car(2, 0, "BMW", "X5", 2015, None)
print myCar.wheels #2
print yourCar.sale_price() #10000

myCar and yourCar are two different instances of the class Car. When we are creating myCar we say that wheels = 4 and when we are creating yourCar - wheels = 2.

When we call the function sale_price the result is different because self.wheels is different for myCar and yourCar instances.