擅长:python、mysql、java
<p>你在找<code>__getitem__</code>吗?在</p>
<pre><code>class C:
def __init__(self):
self.my_property = "Hello"
def __getitem__(self, name):
return getattr(self, name)
c = C()
print c['my_property'] # Prints "Hello"
</code></pre>
<p>或者你在寻找相反的答案,通过<code>__getattr__</code>?在</p>
^{pr2}$
<p>(<strong>编辑</strong>:正如Paul McGuire在评论中所指出的那样,这段代码只展示了完整解决方案的基本原理。)</p>