Dynamic instance attributes

前端 未结 5 1955
春和景丽
春和景丽 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: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)
    

提交回复
热议问题