问题
I am trying to figure out encapsulation in Python. I was doing a simple little test in shell to see how something worked and it doesn't work like I was expecting. And I can't get it to work. Here's 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 into Porche? Thank you.
回答1:
With myCar.set_make=('Porche')
, you are setting this member the Car class as the 'Porche'
string, but you are not calling the method.
Just remove the =
to solve it:
myCar.set_make('Porche')
myCar.get_make() # Porche
Besides, as @DSM points out, there is an error in the argument of set_make
:
def set_make(self, make):
self.__make = make # carMake is not defined!
However, this use of getters and setters in Python is strongly discouraged. If you need something similar for any reason, consider using properties.
回答2:
new_car = Car(...)
new_car2 = Car(...)
new_car._make = 'Ford'
new_car2.make = 'Jetta'
print new_car._make
print new_car2.make
来源:https://stackoverflow.com/questions/15867664/accessor-mutator-methods-python