擅长:python、mysql、java
<p>我能想象的最接近您想要的是使用<code>setattr</code>,它接受一个对象、一个属性名(作为<code>str</code>)和该属性的值。在</p>
<pre><code>class Base(object):
def __init__(self, params):
for k, v in params.iteritems():
if hasattr(self, k):
setattr(self, k, v)
class Child(Base):
def __init__(self, params):
self.field1 = None # create attributes here, not at class level
self.field2 = None
Base.__init__(self, params)
params = dict(
field1 = "one",
field2 = "two",
field3 = "tree", # ignored when used with Child since it has no field3
)
c = Child(params)
</code></pre>