Dynamic instance attributes

前端 未结 5 1916
春和景丽
春和景丽 2021-01-15 16:50

Say i have a class:

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}


        
相关标签:
5条回答
  • 2021-01-15 17:30

    Here is a solution even more outlandish than the one offered by pythonm:

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

    Instead of using inst.d, use inst.__dict__ directly. An added benefit is that new keys added to d automatically become attributes. That's as dynamic as it gets.

    0 讨论(0)
  • 2021-01-15 17:31

    use 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
    >>> 
    
    0 讨论(0)
  • 2021-01-15 17:44
    class Foo(object):
        def __init__(self, attributes):
            self.__dict__.update(attributes)
    

    That would do it.

    >>>foo = Foo({'a': 42, 'b': 999})
    >>>foo.a
    42
    >>>foo.b
    999
    

    You can also use the setattr built-in method:

    class Foo(object):
        def __init__(self, attributes):
            for attr, value in attributes.iteritems():
                setattr(self, attr, value)
    
    0 讨论(0)
  • 2021-01-15 17:50

    You can also use __getattr__.

    class Foo(object):
    
        def __init__(self, d):
            self.d = d
    
        def __getattr__(self, name):
            return self.d[name]
    
    0 讨论(0)
  • 2021-01-15 17:53

    You could do something like this:

    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)
    
    0 讨论(0)
提交回复
热议问题