简体   繁体   中英

Override type-hint of a parameter in __init__

On this code:

class Obj():
    def a(self):
        pass


class ObjChild(Obj):
    def b(self):
        pass


class A:
    def __init__(self, obj: Obj):
        self.obj = obj


class B(A):
    def __init__(self, obj: ObjChild):
        super().__init__(obj)
        
    def kuku(self):
        self.obj.b()

Pycharm warns me about the last line that:

Unresolved attribute reference 'b' for class 'Obj'

But I type-hinted the obj that is being passed in the __init__ to be ObjChild , so it should know statically that self.obj is a ObjChild instance, and would have the b method.

How can I make Pycharm realize that? It messes up my autocompletions in the project.

Make A a Generic :

from typing import Generic, TypeVar


class Obj:
    def a(self):
        pass


_Obj = TypeVar('_Obj', bound=Obj)


class ObjChild(Obj):
    def b(self):
        pass


class A(Generic[_Obj]):
    def __init__(self, obj: _Obj):
        self.obj = obj


class B(A[ObjChild]):
    def __init__(self, obj: ObjChild):
        super().__init__(obj)
        self.obj.b()

Unless you make A a generic, there's no connection between passing an ObjChild to A.__init__ and A.obj being an ObjChild .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM