[Python] Converting an object into a subclass in Python?

Discussão em 'Python' iniciado por Stack, Julho 19, 2025.

  1. Stack

    Stack Membro Participativo

    Lets say I have a library function that I cannot change that produces an object of class A, and I have created a class B that inherits from A.

    What is the most straightforward way of using the library function to produce an object of class B?

    edit- I was asked in a comment for more detail, so here goes:

    PyTables is a package that handles hierarchical datasets in python. The bit I use most is its ability to manage data that is partially on disk. It provides an 'Array' type which only comes with extended slicing, but I need to select arbitrary rows. Numpy offers this capability - you can select by providing a boolean array of the same length as the array you are selecting from. Therefore, I wanted to subclass Array to add this new functionality.

    In a more abstract sense this is a problem I have considered before. The usual solution is as has already been suggested- Have a constructor for B that takes an A and additional arguments, and then pulls out the relevant bits of A to insert into B. As it seemed like a fairly basic problem, I asked to question to see if there were any standard solutions I wasn't aware of.

    Continue reading...

Compartilhe esta Página