Dynamic instance attributes

前端 未结 5 1957
春和景丽
春和景丽 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条回答
  •  猫巷女王i
    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]
    

提交回复
热议问题