Shortest way of creating an object with arbitrary attributes in Python?

前端 未结 11 1014
谎友^
谎友^ 2021-02-01 14:48

Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object shoul

11条回答
  •  滥情空心
    2021-02-01 15:12

    The original code can be streamlined a little by using __dict__:

    In [1]: class data:
       ...:     def __init__(self, **kwargs):
       ...:         self.__dict__.update(kwargs)
       ...: 
    
    In [2]: d = data(foo=1, bar=2)
    
    In [3]: d.foo
    Out[3]: 1
    
    In [4]: d.bar
    Out[4]: 2
    

    In Python 3.3 and greater, this syntax is made available by the types.SimpleNamespace class.

提交回复
热议问题