-1

I have to define a class Vehicle. Each object of the class has two attributes, license (license plate) and year (year of construction), and two methods that return those attributes.

In addition, I have to define a class Car, a derived class of Vehicle, that has two more attributes, dis (displacement) and max (maximum number of people in the car), with methods to know the latter two.

This is the code I tried to write:

class vehicle:
  def __init__(self,License_plate,Year):
    self.license = License_plate
    self.year = Year
  def year(self):
    return self.year
  def license(self):
    return self.license

class car(vehicle):
  def __init__(self,License_plate,Year,Displacement,maximum):
    veicolo.__init__(self, License_plate, Year)
    self.dis = Displacement
    self.max = maximum
  def displacement(self):
    return self.dis
  def max(self):
    return self.max



a = vehicle('ASDFE',1234)             #This is how I tried to run it 
a.year()                              #Here I got an ERROR :
a.license()                           #TypeError: 'int' object is not callable
b = car('ASDERTWWW',1234,7000,2340)
b.displacement()
b.max()

I have some problem with class in Python. I can not understand the use of a derived class.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • You are using the same names for the attribute and the method; this is a very bad idea. In fact, you don't need the methods at all; you can just access the attribute directly (or use a `@property` - see e.g. http://stackoverflow.com/q/6618002/3001761). – jonrsharpe Feb 03 '15 at 11:22
  • http://www.memonic.com/user/pneff/folder/development/id/1ttgT – Jasper Feb 03 '15 at 11:27
  • Yaay ! I understood my problem ! Thank man :) – Roberto Pavia Feb 08 '15 at 16:25

2 Answers2

1

In python we don't need getters and setters.

class Vehicle(object):
    def __init__(self, year):
        self.year = year

class Car(Vehicle):
    def __init__(self, name, year):
        super(Car, self).__init__(year)
        self.name = name 

a = Vehicle(1995)
print a.year
b = Car("test", 1992)
print b.name
print b.year
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
0

You have a method and a variable with the same name. When you call a.year() you are trying to call the year variable.

One solution would be to rename one of them (either the variable to _year or the method to getYear). Alternatively you could just access the variables directly. Nothing is private in python so you can just do >>> a.year -> 1234

Holloway
  • 6,412
  • 1
  • 26
  • 33