pythonvlc

Python inheritance, not returning new class


I'm having problems understanding why the inheritance is not working in the following example:

import vlc

class CustomMediaPlayer(vlc.MediaPlayer):

    def __init__(self, *args):
        super().__init__(*args)

    def custom_method(self):
        print("EUREKA")

custom_mp = CustomMediaPlayer()
print(custom_mp)
custom_mp.custom_method()

This outputs:

<vlc.MediaPlayer object at 0x7743d37db8f0>

AttributeError: 'MediaPlayer' object has no attribute 'custom_method'

instead of a CustomMediaPlayer object, with the custom_method.

Why is this happening? Is it because vlc.MediaPlayer is a _Ctype class?


Solution

  • This can happen if the base class overrides the __new__ method, which controls what happens when someone attempts to instantiate the class. The typical behaviour is that a new instance of the given class argument is created; but the __new__ function is free to return an existing object, or create an object according to its own internal logic.

    In their comment, Rogue links to the source code for the module, which does indeed override __new__. If there is a way to subclass vlc.MediaPlayer successfully, it should be listed in the module's documentation; otherwise the way to address this problem will depend on your specific requirements.