Struct Embedding in Assembly Language

Embedding Structs and Methods in Python

Python supports a form of composition through object attributes. While Python doesn’t have explicit struct embedding like other languages, similar functionality can be achieved using class inheritance or including instances of one class as attributes of another.

class Base:
    def __init__(self, num):
        self.num = num

    def describe(self):
        return f"Base with num={self.num}"

class Container:
    def __init__(self, num, string):
        self.base = Base(num)
        self.str = string

def main():
    co = Container(1, "some name")

    # Directly access the base's fields through the container
    print(f"co={{num: {co.base.num}, str: {co.str}}}")

    # Alternatively, access the base's fields explicitly
    print(f"also num: {co.base.num}")

    # Calling the describe method from Base through the Container
    print(f"describe: {co.base.describe()}")

    # Using a protocol (interface) in Python modeled with a class
    class Describer:
        def describe(self):
            pass

    # Assign co.base to a variable of type Describer to show interface implementation
    d = co.base
    print(f"describer: {d.describe()}")

if __name__ == "__main__":
    main()

To run the program, save it in a file named struct_embedding.py and use Python to execute it.

$ python struct_embedding.py

This will produce the following output:

co={num: 1, str: some name}
also num: 1
describe: Base with num=1
describer: Base with num=1

By utilizing class inheritance, object attributes, and Python’s dynamic nature, we can achieve functionality similar to struct embedding and method extension.