访问器和修改器方法 (Python)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15867664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:13:35  来源:igfitidea点击:

Accessor & Mutator methods (Python)

pythonmutators

提问by user2255444

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:

我想弄清楚 Python 中的封装。我在 shell 中做了一个简单的小测试,看看某些东西是如何工作的,它不像我期望的那样工作。我无法让它工作。这是我的代码:

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.

为什么 myCar.set_make 不把福特变成保时捷?谢谢你。

采纳答案by A. Rodas

With myCar.set_make=('Porche'), you are setting this member the Car class as the 'Porche'string, but you are not calling the method.

使用myCar.set_make=('Porche'),您将此成员设置为 Car 类作为'Porche'字符串,但您没有调用该方法。

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:

此外,正如@DSM 指出的那样, 的参数存在错误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.

但是,强烈建议不要在 Python 中使用 getter 和 setter。如果您出于任何原因需要类似的东西,请考虑使用properties

回答by Tim Conroy

new_car = Car(...)
new_car2 = Car(...)

new_car._make = 'Ford'
new_car2.make = 'Jetta'

print new_car._make
print new_car2.make