Structs in R Programming Language

Structs in Python

Python’s class allows you to create custom data structures like structs. They’re useful for grouping data together to form records.

This Person class has name and age fields.

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

The new_person function constructs a new Person object with the given name.

def new_person(name: str) -> Person:
    return Person(name=name)

Python handles memory management and garbage collection, so you can safely return object references and rely on the garbage collector to clean up when there are no active references to an object.

Here’s how you can create and use Person objects.

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

    # You can name the fields when initializing an instance.
    print(Person(name="Alice", age=30))

    # Omitted fields will be initialized with the default value.
    print(Person(name="Fred"))

    # You can get a reference to an instance directly.
    print(Person(name="Ann", age=40))

    # Using the constructor function
    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 object references; Python automatically handles dereferencing.
    sp = s
    print(sp.age)

    # Instances are mutable.
    sp.age = 51
    print(sp.age)

    # If a class is only used for a single value, you don’t have to give it a name.
    # This technique is commonly used for table-driven tests.
    Dog = type("Dog", (object,), {"name": "Rex", "is_good": True})
    dog = Dog()
    print(dog.name, dog.is_good)

if __name__ == "__main__":
    main()

Run the above script.

$ python structs.py

You will observe the following output:

<__main__.Person object at 0x7f3e3e09d0d0>
<__main__.Person object at 0x7f3e3e09d190>
<__main__.Person object at 0x7f3e3e09d1d0>
<__main__.Person object at 0x7f3e3e09d210>
<__main__.Person object at 0x7f3e3e09d250>
Sean
50
51
Rex True

Next example: Methods.