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

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

    This works in 2.5, 2.6, and 3.1:

    class Struct(object):
        pass
    
    something = Struct()
    something.awesome = abs
    
    result = something.awesome(-42)
    

    EDIT: I thought maybe giving the source would help out as well. http://docs.python.org/tutorial/classes.html#odds-and-ends

    EDIT: Added assignment to result, as I was using the interactive interpreters to verify, and you might not be.

提交回复
热议问题