Create an anonymous class instance in python

前端 未结 5 1549
礼貌的吻别
礼貌的吻别 2020-12-29 04:44

Sometimes i need to create an anonymous class instance in python, just like c#:

var o= new {attr1=\"somehing\", attr2=344};

but in python i

5条回答
  •  悲哀的现实
    2020-12-29 05:19

    I prefer the dict answer from mwhite, but here's how I've done it in the past using the "magic" of kwargs (pun intended).

    class ObjectFromDict(object):
        def __init__(**kwargs):
            for k in kwargs:
                if k not in self.__dict__:
                    setattr(k,v)
    
    myObj = ObjectFromDict(**{'foo': 'bar', 'baz': 'monkey'})
    print myObj.foo #bar
    

提交回复
热议问题