Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inheritance, not returning new class

Tags:

python

vlc

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?

like image 360
stack92 Avatar asked Oct 29 '25 10:10

stack92


1 Answers

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.

like image 174
khelwood Avatar answered Oct 30 '25 23:10

khelwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!