擅长:python、mysql、java
<p>如果您想添加字典,Mathias的答案就足够用python中的<a href="https://docs.python.org/release/1.5.1p1/tut/keywordArgs.html" rel="noreferrer">key word arguments</a>了。</p>
<p>但是,如果希望从关键字参数中添加对象变量,则需要<a href="https://docs.python.org/2/library/functions.html#setattr" rel="noreferrer">setattr</a></p>
<p>例如,如果你想要这样的东西:</p>
<pre><code>student1 = Student("Edward", "Gates", "0456789", {'math': 100, 'bio': 90, 'history': 80})
print student1.math #prints 100
print student1.bio #prints 90
</code></pre>
<p>这样就可以做到:</p>
<pre><code>class Student(object):
def __init__(self, first_name, last_name, id, **kwargs):
self.first_name = first_name
self.last_name = last_name
self.id = id
for key, value in kwargs.iteritems():
setattr(self, key, value)
student1 = Student("Edward", "Gates", "0456789", {'math': 100, 'bio': 90, 'history': 80})
</code></pre>
<p>请注意,<strong>**kwargs</strong>将只解包字典或元组的元组。如果要发送不带键的值列表,则应使用<strong>*args</strong>。查看<a href="https://docs.python.org/release/1.5.1p1/tut/keywordArgs.html" rel="noreferrer">here</a>了解更多信息。</p>