lol*_*lol 15 python python-2.7
这是如何在Python中定义属性为"Speed"的类"Car"?我的背景是Java,似乎没有在Python中使用get/set方法.
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
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 25
在Python中,我们通常避免使用 getter和setter.只是有一个.speed属性:
class Car(object):
speed = 0
def __init__(self):
self.speed = 100
Run Code Online (Sandbox Code Playgroud)
请参阅Python不是Java的动机和更多陷阱要避免:
在Java中,您必须使用getter和setter,因为使用公共字段使您无法返回并在以后使用getter和setter改变主意.所以在Java中,你可能也会提前做好准备工作.在Python中,这很愚蠢,因为您可以从普通属性开始并随时改变主意,而不会影响该类的任何客户端.所以,不要写getter和setter.
使用property时,你有真正需要时获取,设置或删除属性来执行代码.验证,缓存,副作用等都是属性的公平使用案例.只是在必要时不要使用它们.
| 归档时间: |
|
| 查看次数: |
19881 次 |
| 最近记录: |