Namedtuple like class

后端 未结 5 2012
有刺的猬
有刺的猬 2021-02-06 01:27

I find myself writing this class often in my python code when I need a quick single use class.

class Struct(object):
   def __init__( self, **kwargs ):
      for          


        
5条回答
  •  眼角桃花
    2021-02-06 02:08

    What you have is a perfectly reasonable prototype, but you're right that it doesn't scale.

    If you like using them, but want to have a path to better code later, here's what I'd suggest:

    • every time you do that, subclass Structure:

      class Control(Structure): pass

    • later, when you want a "real" class, replace the superclass with something like strongbox.Strongbox (example usage) that provides that same constructor and attribute interface, but constrains which slots you can fill in.

    A discipline like this only costs you one extra line up front, and won't break your code if you want more power later.

提交回复
热议问题