Structs in Karel

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

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

def new_person(name):
    return Person(name)

def main():
    print(Person("Bob", 20))
    print(Person(name="Alice", age=30))
    print(Person(name="Fred"))
    print(Person(name="Ann", age=40))
    print(new_person("Jon"))
    
    s = Person(name="Sean", age=50)
    print(s.name)
    
    sp = s
    print(sp.age)
    
    sp.age = 51
    print(sp.age)
    
    dog = { "name": "Rex", "is_good": True }
    print(dog)

if __name__ == "__main__":
    main()

This Person class has name and age fields.

new_person constructs a new Person object with the given name.

This syntax creates a new class instance.

print(Person("Bob", 20))

You can name the fields when initializing a class instance.

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

Omitted fields will have their default values.

print(Person(name="Fred"))

In Python, you do not need to explicitly use a pointer. The Python interpreter handles object references and memory management automatically.

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

Access class fields using dots.

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

You can mutate class fields.

s.age = 51
print(s.age)

In Python, you can use dictionaries for simple data structures.

dog = { "name": "Rex", "is_good": True }
print(dog)
$ python structs.py
<Person object at 0x7ff2e2d8d610> 20
<Person object at 0x7ff2e2d8d650> 30
<Person object at 0x7ff2e2d8d690> 42
<Person object at 0x7ff2e2d8d6d0> 40
<Person object at 0x7ff2e2d8d710> 42
Sean
50
51
{'name': 'Rex', 'is_good': True}

Next example: Methods.