vendredi 15 avril 2022

Wrap object in custom Python class adding extra logic

A Python library provides a function create_object that creates an object of type OriginalClass.

I would like to create my own class so that it takes the output of create_object and adds extra logic (on top of what create_object already does). Also, that new custom object should have all the properties of the base object.

So far I've attempted the following:

class MyClass(OriginalClass):
  
  def __init__(self, *args, **kwargs):
    super(MyClass, self).__init__(args, kwargs)

This does not accomplish what I have in mind. Since the function create_object is not called and the extra logic handled by it not executed.

Also, I do not want to attach the output of create_object to an attribute of MyClass like so self.myobject = create_object(), since I want it to be accessed by just the instantiation of an object of type MyClass.

What would be the best way to achieve that functionality in Python? Does that corresponds to an existing design pattern?

I am new to Python OOP so maybe the description provided is too vague. Please feel free to request in depth description from those vaguely described parts.

Aucun commentaire:

Enregistrer un commentaire