擅长:python、mysql、java
<blockquote>
<p>So my question is this: do "instance properties" exist?</p>
</blockquote>
<p>没有</p>
<blockquote>
<p>If not, what is the reason?</p>
</blockquote>
<p>因为属性被实现为<a href="http://docs.python.org/2/howto/descriptor.html" rel="nofollow">descriptors</a>。描述符的神奇之处在于,当在对象类型的字典中找到时,它们所做的事情与在对象字典中找到时的不同。在</p>
<blockquote>
<p>I have been able to find lots about how properties are used in Python, but precious little about how they are implemented.</p>
</blockquote>
<p>阅读上面链接的描述指南。在</p>
<hr/>
<p>那么,你有没有办法做到这一点?在</p>
<p>嗯,是的,如果你愿意重新考虑一下设计。在</p>
<p>对于您的例子,您所要做的就是使用<code>_traits</code>代替{<cd2>},并且动态生成无用的getter函数,因此可以用几行代码替换整个过程,就像Martijn Pieters的回答一样。在</p>
<p>或者,如果您想将<code>.foo</code>重定向到<code>._foo</code>如果<code>foo</code>在<code>_traits</code>的列表(或更好的情况下,集合)中,这同样简单:</p>
<pre><code>def __getattr__(self, name):
if name in self._traits:
return getattr(self, '_' + name)
raise AttributeError
</code></pre>
<p>但是假设您实际上对getter函数有某种用途,每个属性实际上需要一些代码来生成值,这个值已经封装在一个函数中,并存储在<code>_traits</code>中。在这种情况下:</p>
^{pr2}$