0

Is there a way to make a generic class A[T], which has a function that inherits the type for the same function in T?

I want to make something like these 2 classes:

class A[T]:
    ...
    def a(self):
        ...

class B(A):
    def a(self, a: int, b:int):
        ...

and have A[B].a's type be (self: B, a: int, b: int) -> None, instead of (self: A) -> None. Is there a way to do this without repeating the type hints in the definition of the B class?

5
  • 3
    FYI that breaks the LSP; def demo(a: A): return a.a() fails for demo(B()), because the subclass method has required arguments the superclass method does not.. Commented Sep 19 at 11:03
  • (a quick workaround is to make the arguments non-mandatory, thanks to default values) Commented Sep 19 at 11:13
  • What does the base class definition do? Does it need the extra arguments? If you need to say the type is A[B] – "this is sort of an A, but you can't use it without knowing it's really a B" – then it might be clearer to make the base class method a "private" helper with a different name, and have the static type of your object be the concrete type B. Commented Sep 19 at 11:23
  • 2
    It's unclear what you mean by A[B] - A doesn't currently use T, and why would that be its own subclass? Maybe you want something like this, but note that tells you the same thing for this specific case: B's implementation of a is not compatible with the supertype. Commented Sep 19 at 12:53
  • This is clearly a legitimate question, and the O.P. needs to be taught about what is expected in inheritance, and LSP in the answer. I don't think this should be closed at all - least why "the O.P. have the wrong premises" - that is what the answers are supposed to tackle. Commented Sep 21 at 15:36

1 Answer 1

-1

I'm not sure if this is what you need, but you can leave out the generic class and make the method in question generic, something like:

from typing import TypeVar

T = TypeVar('T')

class A():
    
    def a( self, st : T ):
        print( f" hello user {st}" )

class B( A ):
    pass

    
objectA = A()
objectA.a( "What are they?!" )
objectB = B()
objectB.a( 118 )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.