<pre><code>class MyClass(object):
def __init__(self):
self.data = {'a': 'v1', 'b': 'v2'}
def __getattr__(self, attr):
return self.data[attr]
</code></pre>
<hr/>
<pre><code>>>> ob = MyClass()
>>> v = ob.a
>>> v
'v1'
</code></pre>
<p>但是,在实现<code>__setattr__</code>时要小心,您需要做一些修改:</p>
<pre class="lang-py prettyprint-override"><code>class MyClass(object):
def __init__(self):
# prevents infinite recursion from self.data = {'a': 'v1', 'b': 'v2'}
# as now we have __setattr__, which will call __getattr__ when the line
# self.data[k] tries to access self.data, won't find it in the instance
# dictionary and return self.data[k] will in turn call __getattr__
# for the same reason and so on.... so we manually set data initially
super(MyClass, self).__setattr__('data', {'a': 'v1', 'b': 'v2'})
def __setattr__(self, k, v):
self.data[k] = v
def __getattr__(self, k):
# we don't need a special call to super here because getattr is only
# called when an attribute is NOT found in the instance's dictionary
try:
return self.data[k]
except KeyError:
raise AttributeError
</code></pre>
<hr/>
<pre><code>>>> ob = MyClass()
>>> ob.c = 1
>>> ob.c
1
</code></pre>
<p>如果不需要设置属性,只需使用namedtuple
例如</p>
<pre><code>>>> from collections import namedtuple
>>> MyClass = namedtuple("MyClass", ["a", "b"])
>>> ob = MyClass(a=1, b=2)
>>> ob.a
1
</code></pre>
<p>如果需要默认参数,可以在其周围编写一个包装类:</p>
<pre><code>class MyClass(namedtuple("MyClass", ["a", "b"])):
def __new__(cls, a="v1", b="v2"):
return super(MyClass, cls).__new__(cls, a, b)
</code></pre>
<p>或者它作为一个函数看起来更好:</p>
<pre><code>def MyClass(a="v1", b="v2", cls=namedtuple("MyClass", ["a", "b"])):
return cls(a, b)
</code></pre>
<hr/>
<pre><code>>>> ob = MyClass()
>>> ob.a
'v1'
</code></pre>