Class factory to produce simple struct-like classes?

后端 未结 7 1440
盖世英雄少女心
盖世英雄少女心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 06:26

    If you're using Python 2.6, try the standard library namedtuple class.

    >>> from collections import namedtuple
    >>> Person = namedtuple('Person', ('forename', 'surname'))
    >>> person1 = Person('John', 'Doe')
    >>> person2 = Person(forename='Adam', surname='Monroe')
    >>> person1.forename
    'John'
    >>> person2.surname
    'Monroe'
    

    Edit: As per comments, there is a backport for earlier versions of Python

提交回复
热议问题