Structs in Mercury

Our goal is to convert the given code example to Python, providing the equivalent constructs and coding style that fit within Python’s conventions. Here’s how you would write and explain the example in Python.

# Python’s classes are used to group data together to form records.
# Here’s how you define a class and create instances of it.

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

# new_person constructs a new Person instance with the given name.
def new_person(name):
    # In Python, you typically return the instance directly.
    p = Person(name)
    p.age = 42
    return p

def main():
    # This syntax creates a new instance of a class.
    print(Person("Bob", 20))

    # You can specify the fields when initializing a class.
    print(Person(name="Alice", age=30))
    
    # Omitted fields will be set to default values.
    print(Person(name="Fred"))
    
    # A & prefix yields a pointer to the struct in Go, but in Python, we just use the instance.
    print(Person(name="Ann", age=40))
    
    # It’s idiomatic to encapsulate new class instance creation in functions.
    print(new_person("Jon"))
    
    # Access class fields with a dot.
    s = Person(name="Sean", age=50)
    print(s.name)
    
    # You can also use dots with class instances.
    sp = s
    print(sp.age)
    
    # Class instances are mutable.
    sp.age = 51
    print(sp.age)
    
    # If a class is only used for a single value, we don’t have to give it a name.
    # Use an anonymous class type here.
    Dog = type('Dog', (object,), {'name': '', 'isGood': False})
    dog = Dog()
    dog.name = "Rex"
    dog.isGood = True
    print(dog)

if __name__ == "__main__":
    main()

To run the program, save the code in a file named structs.py and execute it using Python.

$ python structs.py
<__main__.Person object at 0x7f8790432b80>
<__main__.Person object at 0x7f8790432b50>
<__main__.Person object at 0x7f8790432c70>
<__main__.Person object at 0x7f8790432ca0>
<__main__.Person object at 0x7f8790432cd0>
Sean
50
51
<__main__.Dog object at 0x7f8790432d00>

Now that we can run and build basic Python programs, let’s learn more about the language.