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

前端 未结 11 888
谎友^
谎友^ 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:36

    If I understand your question correctly, you need records. Python classes may be used this way, which is what you do.

    I believe the most pythonic way of dealing with "records" is simply... dictionaries! A class is a sort of dictionary on steroids.

    Your class example data is essentially a way of converting a dictionary into a class.

    (On a side note, I would rather use self.__setattr__(name, kw[name]).)

提交回复
热议问题