存取器变异器方法(Python) [英] Accessor & Mutator methods (Python)

查看:203
本文介绍了存取器变异器方法(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出Python中的封装.我在shell中进行了一个简单的小测试,以了解某些东西是如何工作的以及它是否像我期望的那样工作.而且我无法使其正常工作.这是我的代码:

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'

myCar.set_make为什么不将福特更改为保时捷?谢谢.

Why doesn't myCar.set_make change Ford into Porche? Thank you.

推荐答案

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

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

此外,正如@DSM所指出的,set_make的参数中存在错误:

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!

但是,此用法强烈建议不要使用Python中的getter和setter方法.如果出于任何原因需要类似的东西,请考虑使用属性.

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

这篇关于存取器变异器方法(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆