Python Classes Help


#1



I'm having trouble with the Python exercise Overriding Methods, which is 10/11 of the Classes section of the Python course.



For some reason, I get the following error message:

Traceback (most recent call last):
File "python", line 28, in
TypeError: 'str' object is not callable


The code uses the same syntax as a previous exercise, so it should be working.


class Car(object):
    condition = "new"
    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg = mpg

    def display_car(self):
        return "This is a %s %s with %s MPG. " % (self.color, self.model, self.mpg)

    def drive_car(self):
        self.condition = "used"

class ElectricCar(Car):
    def __init__(self, model, color, mpg, battery_type):
        super(ElectricCar, self).__init__(model, color, mpg)
        self.battery_type = battery_type

    def display_car(self):
       inherit_Str = super(ElectricCar, self).display_car()
       return inherit_Str + "It has a %s battery. " % (self.battery_type)
    
    def drive_car(self):
        self.condition = "like new"

my_car = ElectricCar("Ford", "black", 95, "molten salt")
print my_car.display_car()
print my_car.condition()
my_car.drive_car()
print my_car.condition()


The error message refers to my calling my_car.condition(), but is exactly the same as a previous exercise, just using a child object instead. The other one worked fine, but now won't work here either.


#2

here:

print my_car.condition()

what is condition? condition is a member variable. by using parentheses it becomes a method call, but condition is no method

so my_car is your object instance, to call a member variable the following syntax is required:

instance.methodname

hope this helps


#3

That makes sense. After all, displaying a member variable would be the same as a normal variable, just referencing the object. It works now, thank you!


#4