While investigating Ruby I came across this to create a simple Struct-like class:
Person = Struct.new(:forname, :surname)
person1 = Person.new(\'John\', \'Do
If you're running python <2.6 or would like to extend your class to do more stuff, I would suggest using the type()
builtin. This has the advantage over your solution in that the setting up of __dict__
happens at class creation rather than instantiation. It also doesn't define an __init__
method and thus doesn't lead to strange behavior if the class calls __init__
again for some reason. For example:
def Struct(*args, **kwargs):
name = kwargs.pop("name", "MyStruct")
kwargs.update(dict((k, None) for k in args))
return type(name, (object,), kwargs)
Used like so:
>>> MyStruct = Struct("forename", "lastname")
Equivalent to:
class MyStruct(object):
forename = None
lastname = None
While this:
>>> TestStruct = Struct("forename", age=18, name="TestStruct")
Is equivalent to:
class TestStruct(object):
forename = None
age = 18
Update
Additionally, you can edit this code to very easily prevent assignment of other variables than the ones specificed. Just change the Struct() factory to assign __slots__.
def Struct(*args, **kwargs):
name = kwargs.pop("name", "MyStruct")
kwargs.update(dict((k, None) for k in args))
kwargs['__slots__'] = kwargs.keys()
return type(name, (object,), kwargs)