Structs in Squirrel

Based on the language specified, the target language is Python. Here is the translation of the provided example into Python along with the explanation.


Python’s classes are used to create complex data structures. They are useful for grouping data together to form records.

This Person class has name and age fields.

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

new_person constructs a new Person object with the given name.

def new_person(name):
    # A new instance of Person is created with the given name
    # The age is set to 42 as a default
    p = Person(name)
    p.age = 42
    return p

Python is a garbage-collected language; you can safely return an object and it will be managed by the garbage collector.

def main():
    # This syntax creates a new object
    print(Person("Bob", 20))
    
    # You can name the fields when initializing an object
    print(Person(name="Alice", age=30))
    
    # Omitted fields will be set to their default values
    print(Person(name="Fred"))
    
    # An & prefix is not needed in Python; objects are implicitly referenced
    print(Person(name="Ann", age=40))
    
    # It's idiomatic to encapsulate new object creation in functions
    print(new_person("Jon"))
    
    # Access object fields with a dot
    s = Person(name="Sean", age=50)
    print(s.name)
    
    # Objects are mutable
    s.age = 51
    print(s.age)

    # Anonymous objects can be created using dictionaries
    dog = {"name": "Rex", "isGood": True}
    print(dog)

if __name__ == "__main__":
    main()

To run the program, save the code into a .py file, and then use python to execute it.

$ python structs.py
<Person object at 0x7f87000e8910>
<Person object at 0x7f87000e8c50>
<Person object at 0x7f87000e8ca0>
<Person object at 0x7f87000e8cd0>
<Person object at 0x7f87000e8d00>
Sean
50
51
{'name': 'Rex', 'isGood': True}

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

Next example: Methods.