开发者

How to use generic classes with a child class that uses a method with an argument hinted to the generic classes's TypeVar?

import typing as typ


T = typ.TypeVar("T", str, int)

class Foo(typ.Generic[T]):
    def method(self, q: T) -> T:
        return q
开发者_开发知识库

class Bar(Foo[str]):
    def method(self, q):
        return q.capitalize()
#              ^^^^^^^^^^^^^ Cannot access member "capitalize" for type "int*"

I'm using vscode's basic type checker using pylance.

How do you remove the error above?


capitalize() method returns only string(works for only a string).

While reproducing, I could observe the similar issue as yours:

a=Foo()
b=Bar()
print(a.method(1),b.method(1))

Error:

How to use generic classes with a child class that uses a method with an argument hinted to the generic classes's TypeVar?

But I didn't observe any issue while passing a string/character to the method function in Bar() class. Your code would work fine if you remove the capitalize function while passing an integer. Or you could add a condition while returning q in Bar() class as follows:

return q if str(q).isdigit() else q.capitalize()

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜