Reputation: 761
I have the following structure:
import abc
class AbstractParent:
pass
class AbstractChild(AbstractParent):
@abc.abstractmethod
def foo(self):
raise NotImplementedError()
class Child(AbstractChild):
def foo(self):
print('!')
class A:
def __init__(self, x: AbstractParent):
self.x = x
class B(A):
def __init__(self, x: Child):
super().__init__(x=x)
def test(self):
return self.x.foo() # Unresolved attribute reference 'foo' for class 'AbstractParent'
What I would expect is that since Child
is a subclass of AbstractParent
and Child
has a method foo
, and since x
is being declared as a Child
in class B
, that foo
is able to be resolved as a method of Child
.
Instead Pycharm has a visual warning Unresolved attribute reference 'foo' for class 'AbstractParent'
Why isn't it able to figure out that x
is a Child
which has method foo
?
Note that setting self.x = x
in B
fixes the issue. Is this a bug?
Upvotes: 2
Views: 101
Reputation: 7579
It could be solved with generics, see the following example:
from typing import Generic, TypeVar
T = TypeVar("T", bound=AbstractParent)
class A(Generic[T]):
x: T
def __init__(self, x: T):
self.x = x
class B(A[Child]):
def __init__(self, x):
super().__init__(x=x)
def test(self):
return self.x.foo()
Feel free to ask any questions.
Upvotes: 1