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

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

    A function is an object. So you could assign attributes to a function. Or make one. This is the simplest way in terms of lines of code, I think.

    def hello():
        pass
    
    
    hello.chook = 123
    

    but the easiest and most elegant way (but Python 3.3+) is to use the standard libary's SimpleNamespace:

    >>> from types import SimpleNamespace
    >>> foo = SimpleNamespace()
    >>> foo.hello = "world"
    

提交回复
热议问题