Structs in Minitab

Here’s the translated code in Python along with explanations in Markdown format suitable for Hugo:

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

This Person class has name and age attributes.

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

new_person constructs a new Person object with the given name.

Python is a garbage collected language; you can safely return a reference to a local variable - it will only be cleaned up by the garbage collector when there are no active references to it.

def new_person(name):
    p = Person(name, 42)
    return p

This syntax creates a new Person object.

print(Person("Bob", 20))

You can name the fields when initializing an object.

print(Person(name="Alice", age=30))

Omitted fields will use default values. In Python, the default would be defined in the __init__ constructor.

print(Person(name="Fred", age=0))  # Assuming default age is 0 if not provided

Prefixing with & is not applicable in Python since it handles references automatically.

print(Person(name="Ann", age=40))

It’s idiomatic to encapsulate new object creation in constructor functions.

print(new_person("Jon"))

Access class attributes with a dot.

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

You can also use dots with object references - the references are automatically managed.

sp = s
print(sp.age)

Classes are mutable.

sp.age = 51
print(sp.age)

If a class type is only used for a single value, we don’t have to give it a name. The value can have an anonymous class type.

This technique is commonly used for table-driven tests.

dog = type("Dog", (object,), {"name": "Rex", "is_good": True})()
print(dog.name, dog.is_good)
$ python struct_example.py
<__main__.Person object at 0x7f9d3c4c5c10>
<__main__.Person object at 0x7f9d3c4c5c70>
<__main__.Person object at 0x7f9d3c4c5b80>
<__main__.Person object at 0x7f9d3c4c5bb0>
<__main__.Person object at 0x7f9d3c4c5be0>
Sean
50
51
Rex True

Next example: Methods.