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

前端 未结 16 1722
长情又很酷
长情又很酷 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 00:56

    There are a few ways to reach this goal. Basically you need an object which is extendable.

    obj.a = type('Test', (object,), {})  
    obj.a.b = 'fun'  
    
    obj.b = lambda:None
    
    class Test:
      pass
    obj.c = Test()
    

提交回复
热议问题