擅长:python、mysql、java
<p>在Python中,我们通常避免使用getter和setter。只要有一个<code>.speed</code>属性:</p>
<pre><code>class Car(object):
speed = 0
def __init__(self):
self.speed = 100
</code></pre>
<p>请参阅<a href="http://dirtsimple.org/2004/12/python-is-not-java.html">Python is not Java</a>了解动机和要避免的更多陷阱:</p>
<blockquote>
<p>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.</p>
</blockquote>
<p>当您在获取、设置或删除属性时真正需要执行代码时,请使用<code>property</code>。验证、缓存、副作用等都是属性的合理用例。只要在必要时才使用它们。</p>