While investigating Ruby I came across this to create a simple Struct-like class:
Person = Struct.new(:forname, :surname) person1 = Person.new('John', 'Doe') puts person1 #<struct Person forname="John", surname="Doe"> Which raised a few Python questions for me. I have written a [VERY] basic clone of this mechanism in Python:
def Struct(*args): class NewStruct: def __init__(self): for arg in args: self.__dict__[arg] = None return NewStruct >>> Person = Struct('forename', 'surname') >>> person1 = Person() >>> person2 = Person() >>> person1.forename, person1.surname = 'John','Doe' >>> person2.forename, person2.surname = 'Foo','Bar' >>> person1.forename 'John' >>> person2.forename 'Foo' Is there already a similar mechanism in Python to handle this? (I usually just use dictionaries).
How would I get the
Struct()function to create the correct__init__()arguments. (in this case I would like to performperson1 = Person('John', 'Doe')Named Arguments if possible:person1 = Person(surname='Doe', forename='John')
I Would like, as a matter of interest, to have Question 2 answered even if there is a better Python mechanism to do this.