Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can subclass methods return a different type than the abstract class in python?

Is this acceptable?

from abc import ABC, abstractmethod
from typing import Any


class A(ABC):
    @abstractmethod
    def test(self) -> Any:
        ...
    
    
class B(A):
    def test(self) -> int:
        return 1
    
class C(A):
    def test(self) -> str:
        return "yes"

To clarify, I know they can, I just want to know if this is acceptable in terms of good practices.

like image 491
SamuelNLP Avatar asked Oct 11 '25 20:10

SamuelNLP


1 Answers

Technically yes, but it would be much better to define a generic return type and have the subclasses return subclasses of this return type.

For example, you could define a class GenericType and have two subclasses GenericTypeA and GenericTypeB. Then you could do something like this:

from abc import ABC, abstractmethod

class A(ABC):
    @abstractmethod
    def test(self) -> GenericType:
        ...
    
    
class B(A):
    def test(self) -> GenericTypeA:
        ...
    
class C(A):
    def test(self) -> GenericTypeB:
        ...

This way class A is telling the user that the test method always returns a GenericType object, which is itself an abstract class. That way the user knows that any subclass of class A will return a subclass of GenericType.

like image 110
mattyx17 Avatar answered Oct 14 '25 13:10

mattyx17