Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiple inheritance from class and protocol

In Python, I have two protocols, one of which inherits from the other:

class SupportsFileOperations(Protocol):
    ...

class SupportsMediaOperations(SupportsFileOperations):
    ...

I then have a couple of concrete classes that implement these protocols, and one inherits from the other.

class File(SupportsFileOperations):
    ...

class MediaFile(File, SupportsMediaOperations):
    def __init__(self):
        File.__init__(self)

My question is, is calling File.__init__(self) in the MediaFile constructor the correct way to initialize this? I'm not sure how multiple inheritance works with protocols.

Thanks!

like image 204
opnightfall1771 Avatar asked Jul 28 '26 12:07

opnightfall1771


2 Answers

You can simply add Protocol in the child class:

from typing import Protocol

class SupportsFileOperations(Protocol):
    ...

class SupportsMediaOperations(SupportsFileOperations, Protocol):
    ...
like image 126
Jean-Francois T. Avatar answered Jul 31 '26 01:07

Jean-Francois T.


When you using protocols in Python you use structural subtyping, so you don't have to inherit the protocol classes. If you want some class to be considered as a subtype of your protocol you just need to implement all methods of protocol with the same function signatures.

like image 24
pingvincible Avatar answered Jul 31 '26 00:07

pingvincible