在 Python 中使用访问器的正确方法?

编程入门 行业动态 更新时间:2024-10-28 07:24:36
本文介绍了在 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 中使用访问器的正确方法?

本文发布于:2023-06-08 06:29:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/576113.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   方法   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!