Does Python have anonymous classes?

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

    Quoted from this page:

     class Struct:
         def __init__(self, **entries): self.__dict__.update(entries)
         def __eq__(self, other): return self.__dict__ == other.__dict__
         def __ne__(self, other): return self.__dict__ != other.__dict__
    
     options = Struct(answer=42, linelen = 80, font='courier')
     options.answer
     >>> 42
     options.answer = 'plastics'
     vars(options)
     >>> {'answer': 'plastics', 'font': 'courier', 'linelen': 80}
    

提交回复
热议问题