Does Python have anonymous classes?

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

    The type(...) form will fail the structural comparison requirement (without getting really ugly). The dict(...) form doesn't meet the attribute accessor requirement.

    The attrdict seems to fall in the middle somewhere:

    class attrdict(dict):
        def __init__(self, *args, **kwargs):
            dict.__init__(self, *args, **kwargs)
            self.__dict__ = self
    
    a = attrdict(x=1, y=2)
    b = attrdict(y=2, x=1)
    
    print a.x, a.y
    print b.x, b.y
    print a == b
    

    But it means defining a special class.

    OK, I just noticed the update to the question. I'll just note that you can specify dict for the bases parameter and only need to specify the constructor then (in the icky type expression). I prefer attrdict. :-)

提交回复
热议问题