Create an anonymous class instance in python

前端 未结 5 1550
礼貌的吻别
礼貌的吻别 2020-12-29 04:44

Sometimes i need to create an anonymous class instance in python, just like c#:

var o= new {attr1=\"somehing\", attr2=344};

but in python i

5条回答
  •  猫巷女王i
    2020-12-29 05:16

    type

    while this is not precisely a single statement I think creating a wrapper around the magic of the accepted answer makes it by far more readable.

    import inspect 
    
    # wrap the type call around a function 
    # use kwargs to allow named function arguments
    def create_type(name, **kwargs):
        return type(name, (object,), kwargs)
    
    # example call to make a structure
    p = create_type('foobar', xxx='barfoo', seti=0)
    
    assert p.xxx == 'barfoo'
    assert p.seti == 0
    
    print inspect.getmembers(p)
    

    Output

    [('__class__', ),
     ('__delattr__', ),
     ('__dict__', ),
     ('__doc__', None),
     ('__format__', ),
     ('__getattribute__', ),
     ('__hash__', ),
     ('__init__', ),
     ('__module__', '__main__'),
     ('__new__', ),
     ('__reduce__', ),
     ('__reduce_ex__', ),
     ('__repr__', ),
     ('__setattr__', ),
     ('__sizeof__', ),
     ('__str__', ),
     ('__subclasshook__', ),
     ('__weakref__', ),
     # here they are
     ('seti', 0),
     ('xxx', 'barfoo')]
    

    namedtuple

    from collections import namedtuple
    
    d = { 'a' : 'foo', 'b' : 'bar' }
    foobar = namedtuple('foobar', d.keys())(**d)
    print foobar
    

    Output

    Python 2.7.5 (default, May 30 2013, 16:55:57) [GCC] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from collections import namedtuple
    >>> d  =  { 'a' : 'foo', 'b' : 'bar' }
    >>> foobar = namedtuple('foobar', d.keys())(**d)
    >>> print foobar
    foobar(a='foo', b='bar')
    >>> 
    

提交回复
热议问题