Class factory to produce simple struct-like classes?

后端 未结 7 1425
盖世英雄少女心
盖世英雄少女心 2020-12-08 05:47

While investigating Ruby I came across this to create a simple Struct-like class:

Person = Struct.new(:forname, :surname)
person1 = Person.new(\'John\', \'Do         


        
7条回答
  •  攒了一身酷
    2020-12-08 06:13

    As others have said, named tuples in Python 2.6/3.x. With older versions, I usually use the Stuff class:

    class Stuff(object):
        def __init__(self, **kwargs):
            self.__dict__.update(kwargs)
    
    john = Stuff(forename='John', surname='Doe')
    

    This doesn't protect you from mispellings though. There's also a recipe for named tuples on ActiveState:

    http://code.activestate.com/recipes/500261/

提交回复
热议问题