Python supports composition of types through a concept similar to embedding, often referred to as composition or delegation. This is different from inheritance and allows for a more flexible design.
This Python code demonstrates a concept similar to struct embedding in Go, using composition. Here’s how it works:
We define a Base class with a num attribute and a describe method.
We create a Container class that composes a Base instance. It also has its own string attribute.
The Container class delegates the describe method to its composed Base instance.
In the main function, we create a Container instance, demonstrating how to initialize both the container and its composed base.
We show how to access the base’s fields through the base attribute of the container.
We demonstrate calling the delegated describe method on the container.
Finally, we show how Python’s duck typing allows us to use the Container instance wherever an object with a describe method is expected, similar to interface implementation in Go.
To run the program:
This example illustrates how Python can achieve similar functionality to Go’s struct embedding through composition and delegation. While the syntax and some concepts differ, the core idea of composing types and behaviors is preserved.