说我有一堂课:
class Foo(object):
def __init__(self,d):
self.d=d
d={'a':1,'b':2}
inst=Foo(d)
inst.d
Out[315]: {'a': 1, 'b': 2}
有没有办法动态地创建 n 个属性,其中每个属性都是一个 dict 键,所以inst.a
会返回1
等等。
说我有一堂课:
class Foo(object):
def __init__(self,d):
self.d=d
d={'a':1,'b':2}
inst=Foo(d)
inst.d
Out[315]: {'a': 1, 'b': 2}
有没有办法动态地创建 n 个属性,其中每个属性都是一个 dict 键,所以inst.a
会返回1
等等。
class Foo(object):
def __init__(self, attributes):
self.__dict__.update(attributes)
这样就可以了。
>>>foo = Foo({'a': 42, 'b': 999})
>>>foo.a
42
>>>foo.b
999
您还可以使用setattr
内置方法:
class Foo(object):
def __init__(self, attributes):
for attr, value in attributes.iteritems():
setattr(self, attr, value)
使用setattr()
:
>>> class foo(object):
def __init__(self, d):
self.d = d
for x in self.d:
setattr(self, x, self.d[x])
>>> d = {'a': 1, 'b': 2}
>>> l = foo(d)
>>> l.d
{'a': 1, 'b': 2}
>>> l.a
1
>>> l.b
2
>>>
这是一个比 pythonm 提供的更古怪的解决方案:
class Foo(object):
def __init__(self, d):
self.__dict__ = d
而不是使用inst.d
,inst.__dict__
直接使用。另一个好处是添加的新键d
自动成为属性。这是动态的。
你可以这样做:
class Foo(object):
def __init__(self, **kwdargs):
self.__dict__.update(kwdargs)
d = {'a':1,'b':2}
foo = Foo(**d)
foo2 = Foo(a=1, b=2)
您也可以使用__getattr__
.
class Foo(object):
def __init__(self, d):
self.d = d
def __getattr__(self, name):
return self.d[name]