Does Python have anonymous classes?

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

    I don't remember offhand if there's a built-in but writing it yourself is shorter than typing your question. :-)

    class record(object):
      def __init__(self, **kwargs): self.__dict__ = kwargs
      def __eq__(self, r2): return self.__dict__ == r2.__dict__
      def __ne__(self, r2): return self.__dict__ != r2.__dict__
    
    foo = record(x=1, y=2)
    bar = record(y=2, x=1)
    foo == bar  # => true
    

提交回复
热议问题