在 Python 中使用访问器的正确方法? [英] Correct way to use accessors in Python?

查看:60
本文介绍了在 Python 中使用访问器的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在 Python 中定义具有属性Speed"的类Car"的方式吗?我的背景是 Java,似乎没有在 Python 中使用 get/set 方法.

class Car(object):def __init__(self):self._speed = 100@财产定义速度(自我):返回 self._speed@speed.setter定义速度(自我,价值):self._speed = 值

解决方案

在 Python 中,我们通常避免 getter 和 setter.只要有一个 .speed 属性:

class Car(object):速度 = 0def __init__(self):self.speed = 100

请参阅 Python 不是 Java,了解动机和要避免的更多陷阱:><块引用>

在 Java 中,您必须使用 getter 和 setter,因为使用公共字段使您没有机会在以后改变主意使用 getter 和 setter.因此,在 Java 中,您最好先将繁琐的工作排除在外.在 Python 中,这很愚蠢,因为您可以从普通属性开始并随时改变主意,而不会影响该类的任何客户端.所以,不要写 getter 和 setter.

当您在获取、设置或删除属性时确实需要执行代码时,请使用property.验证、缓存、副作用等都是属性的合理用例.除非必要,否则不要使用它们.

Is this how you would define a class "Car" with attribute "Speed" in Python? My background is in Java, and it seems one does not use get/set methods in Python.

class Car(object):
    def __init__(self):
        self._speed = 100

    @property
    def speed(self):
        return self._speed

    @speed.setter
    def speed(self, value):
        self._speed = value

解决方案

In Python we generally avoid getters and setters. Just have a .speed attribute:

class Car(object):
    speed = 0

    def __init__(self):
        self.speed = 100

See Python is not Java for motivations and more pitfalls to avoid:

In Java, you have to use getters and setters because using public fields gives you no opportunity to go back and change your mind later to using getters and setters. So in Java, you might as well get the chore out of the way up front. In Python, this is silly, because you can start with a normal attribute and change your mind at any time, without affecting any clients of the class. So, don't write getters and setters.

Use property when you have a genuine need to execute code when getting, setting or deleting an attribute. Validation, caching, side effects, etc. all are fair use-cases for properties. Just don't use them until necessary.

这篇关于在 Python 中使用访问器的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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