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

前端 未结 16 1725
长情又很酷
长情又很酷 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:07

    These solutions are very helpful during testing. Building on everyone else's answers I do this in Python 2.7.9 (without staticmethod I get a TypeError (unbound method...):

    In [11]: auth = type('', (), {})
    In [12]: auth.func = staticmethod(lambda i: i * 2)
    In [13]: auth.func(2)
    Out[13]: 4
    

提交回复
热议问题