Does Python have anonymous classes?

后端 未结 8 1327
旧巷少年郎
旧巷少年郎 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:11

    1) See http://uszla.me.uk/space/blog/2008/11/06. You can create an anonymous object with slightly ugly syntax by using the type built-in function:

     anon_object_2 = type("", (), {})()
    

    where the 3rd parameter is the dict that will contain the fields of your object.

     foo = type("", (), dict(y=1))()
     foo.y == 1
    

    2) Another variation is proposed by Peter Norvig at http://norvig.com/python-iaq.html. It is also similar to the answer posted by Ken.

    class Struct:
        def __init__(self, **entries): self.__dict__.update(entries)
    
    >>> options = Struct(answer=42, linelen = 80, font='courier')
    >>> options.answer
    42
    

    The benefit of this method is that you can implement equality by contents of the dict, which the first option doesn't have.

    0 讨论(0)
  • 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!)

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