Accessor & Mutator Methods (Python)

I am trying to calculate encapsulation in Python. I did a simple little test in the shell to see how something works and it does not work as I expected. And I can’t make it work. Here is my code:

class Car: def __init__(self, carMake, yrMod): self.__make = carMake self.__yearModel = yrMod self.__speed = 0 #Mutator Methods def set_make(self, make): self.__make = carMake def set_model(self, yrMod): self.__yearModel = yrMod #def set_speed(self, speed): #self.__speed = speed #Accessor Methods def get_make(self): return self.__make def get_yearModel(self): return self.__yearModel def get_speed(self): return self.__speed myCar=Car('Ford', 1968) myCar2=Car('Nissan', 2012) myCar.get_make() 'Ford' myCar.set_make=('Porche') myCar.get_make() 'Ford' 

Why doesn't myCar.set_make change Ford in Porche? Thanks.

+4
source share
2 answers

With myCar.set_make=('Porche') you set this element with the Car class as the string 'Porche' , but you do not call this method.

Just remove = to solve this problem:

 myCar.set_make('Porche') myCar.get_make() # Porche 

Also, as @DSM points out, there is an error in the set_make argument:

 def set_make(self, make): self.__make = make # carMake is not defined! 

However, this use of getters and setters in Python is very discouraged . If you need something like this for any reason, consider using properties .

+6
source
 new_car = Car(...) new_car2 = Car(...) new_car._make = 'Ford' new_car2.make = 'Jetta' print new_car._make print new_car2.make 
-1
source

All Articles