Dynamic instance attributes

前端 未结 5 1915
春和景丽
春和景丽 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.

提交回复
热议问题