ModularM
Modular2y ago
10 replies
Martin Dudek

Seeking Advice on Porting Python Classes to Mojo Structs

I still struggle with how to port Python classes to Mojo structs in the current state of Mojo and seek some help. Here I post a Python class and suggest four ways to port it to Mojo that I came up with. All of them work in this simple example but seem to have some major drawbacks when the class is more complex.

It would be great to get feedback on how you handle this.

Here an example Python class to port to Mojo

class Animal:
    def __init__(self, name):
        self.name = name  
    def whoareyou(self):
        return f"I am {self.name}!"
    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.whoareyou()) # Output: I am Buddy!
print(cat.whoareyou()) # Output: I am Whiskers!
print(dog.speak())  # Output: Buddy says Woof!
print(cat.speak())  # Output: Whiskers says Meow!
Was this page helpful?