2

说我有一堂课:

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等等。

4

5 回答 5

3
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)
于 2012-10-09T19:09:05.257 回答
2

使用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
>>> 
于 2012-10-09T19:09:44.380 回答
1

这是一个比 pythonm 提供的更古怪的解决方案:

class Foo(object):
    def __init__(self, d):
        self.__dict__ = d

而不是使用inst.dinst.__dict__直接使用。另一个好处是添加的新键d自动成为属性。这是动态的。

于 2012-10-09T19:29:17.427 回答
0

你可以这样做:

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)
于 2012-10-09T20:53:36.553 回答
0

您也可以使用__getattr__.

class Foo(object):

    def __init__(self, d):
        self.d = d

    def __getattr__(self, name):
        return self.d[name]
于 2012-10-09T20:57:26.553 回答