How can I create an object and add attributes to it?

前端 未结 16 1733
长情又很酷
长情又很酷 2020-11-28 00:36

I want to create a dynamic object (inside another object) in Python and then add attributes to it.

I tried:

obj = someobject
obj.a = object()
setattr         


        
16条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 01:17

    Now you can do (not sure if it's the same answer as evilpie):

    MyObject = type('MyObject', (object,), {})
    obj = MyObject()
    obj.value = 42
    

提交回复
热议问题