Search code examples
pythonreturn-type

Python - Specify parent or interface as return type


I am new to Python, and trying to understand how we can achieve something like below in python like we do in Java.

public interface IParent {
}

public Class Parent1 implements IParent{
}

public Class Parent2 implements IParent{
}

Now, I can use like:

IParent p1 = new Parent1();
IParent p2 = new Parent2();

So, trying to understand how we can achieve this in Python. Seen some SO articles with TypeVar("T") but couldn't understand. or How we can know what's the return type of any class.

Appreciate any light here.


Solution

  • In Python there is no such thing as interfaces. Instead, use inheritance and so-called abstract base classes (ABC), which, to put it simply, are classes that cannot be instantiated. Your code would translate to:

    from abc import ABC
    
    class IParent(ABC):
        pass
    
    class Parent1(IParent):
        pass
    
    class Parent2(IParent):
        pass
    
    
    p1 = Parent1()
    p2 = Parent2()
    

    Please refer to this article for a more detailed explanation.