Structs in Python

Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

This person struct type has name and age fields.

class Person:
    def __init__(self, name):
        self.name = name
        self.age = 0

def new_person(name):
    p = Person(name)
    p.age = 42
    return p

if __name__ == "__main__":
    print(Person("Bob").__dict__)
    print(Person("Alice").__dict__)
    print(Person("Fred").__dict__)

    print(vars(Person(name="Ann", age=40)))
    print(new_person("Jon").__dict__)

    s = Person("Sean")
    s.age = 50
    print(s.name)
    print(s.age)

    sp = s
    print(sp.age)

    sp.age = 51
    print(sp.age)

    # Anonymous struct-like class
    dog = type("Dog", (object,), {"name": "Rex", "isGood": True})()
    print(vars(dog))

To run this Python code, put the code in a file named structs.py and use the Python interpreter to execute it.

$ python structs.py
{'name': 'Bob', 'age': 0}
{'name': 'Alice', 'age': 0}
{'name': 'Fred', 'age': 0}
{'name': 'Ann', 'age': 40}
{'name': 'Jon', 'age': 42}
Sean
50
50
51
{'name': 'Rex', 'isGood': True}

Next example: Methods.