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

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

    This is typically something you would use a dict for, not making a class at all.

    0 讨论(0)
  • 2021-02-01 15:19

    type('', (), {})() will create an object that can have arbitrary attributes.

    Example:

    obj = type('', (), {})()
    obj.hello = "hello"
    obj.world = "world"
    print obj.hello, obj.world #will print "hello world"
    

    type() with three arguments creates a new type.

    The first argument '' is the name of the new type. We don't care about the name, so we leave it empty.

    The second argument () is a tuple of base types, here object (implicit).

    The third argument is a dictionary of attributes of the new object - again we don't care to it's an empty dictionary {}

    And in the end we instantiate a new instance of this new type with () at the end.

    0 讨论(0)
  • 2021-02-01 15:25

    If you don't need to pass values in the constructor, you can do this:

    class data: pass
    
    data.foo = 1
    data.bar = 2
    

    You use the class static member variables to hold your data.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 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]).)

    0 讨论(0)
提交回复
热议问题