Does Python have anonymous classes?

后端 未结 8 1341
旧巷少年郎
旧巷少年郎 2020-11-30 23:26

I\'m wondering if Python has anything like the C# anonymous classes feature. To clarify, here\'s a sample C# snippet:

var foo = new { x = 1, y = 2 };
var bar          


        
8条回答
  •  臣服心动
    2020-12-01 00:12

    The pythonic way would be to use a dict:

    >>> foo = dict(x=1, y=2)
    >>> bar = dict(y=2, x=1)
    >>> foo == bar
    True
    

    Meets all your requirements except that you still have to do foo['x'] instead of foo.x.

    If that's a problem, you could easily define a class such as:

    class Bunch(object):
        def __init__(self, **kwds):
            self.__dict__.update(kwds)
    
        def __eq__(self, other):
            return self.__dict__ == other.__dict__
    

    Or, a nice and short one

    class Bunch(dict):
        __getattr__, __setattr__ = dict.get, dict.__setitem__
    

    (but note that this second one has problems as Alex points out in his comment!)

提交回复
热议问题