class Parent:
def getSelf(self) -> "Parent":
return self
class Child(Parent):
# 这儿继承 Parent 类, self.getSelf 应当返回"Child", 但是类型提示中仍然是"Parent"
# 难道每一个继承 Parent 类的, 都要重新声明 getSelf 函数吗?
# ...
def getSelf(self) -> "Child":
return self
class Parent:
def getSelf(self) -> "Parent":
return self
class Child(Parent):
# 这儿继承 Parent 类, self.getSelf 应当返回"Child", 但是类型提示中仍然是"Parent"
# 难道每一个继承 Parent 类的, 都要重新声明 getSelf 函数吗?
# ...
def getSelf(self) -> "Child":
return self
|
zhoudaiyuApr 20, 2020
1
|
|
zachlhbApr 20, 2020 via Android
2
写 self 呢,其实可以不用写返回类型
|
|
3
T = TypeVar('T', bound='Parent')
class Parent: def get_self(self) -> T: return self class Child(Parent): pass |
|
wellscApr 20, 2020 via Android
4
不用返回
|
|
HstarApr 20, 2020
5
这代码怎么看起来一股 Java 味
|
|
InkStoneApr 20, 2020
6
如果你不重新声明的话,返回类型确实是 Parent 而不是 Child 啊。
|
|
7
感觉 3 楼回复还要稍微改一下
def get_self(self: T) -> T: |
|
8
|
|
lithbitrenApr 20, 2020
9
一股 java 味,真实
|
|
LiyiwApr 20, 2020
10
学到了
|
|
0dJ6Tu8Za734L89TApr 20, 2020
11
这怎么一股 Java 味。。。
|
|
zhustecApr 20, 2020 via Android
12
我之前也碰到类似的问题就是使用 dataclass 和 typing 时如何只是当前类,比如写链表时节点类表示指向下一个节点。
|
|
lxy42Apr 20, 2020
13
网上查了一下, 这个 issue 使用了前面两位提到的 TypeVar 方法: https://github.com/python/typing/issues/271
|
|
zhoudaiyuApr 20, 2020
14
|
|
raymanrApr 20, 2020
16
呃,没看懂,干嘛返回自身这个实例?
|
|
19
|
|
20
@chenxytw 字符串确实能解决,但是我不可能每一个继承的自带都重写一下,如果我有十几个类要继承,总不能都重写一下吧(虽然我目前就是这么做的。。。)
|
|
caleaseApr 21, 2020
21
|
|
lizytalkApr 21, 2020 via iPhone
22
用引号包起来就行了
|
|
InkStoneApr 21, 2020
23
@xiaoming1992 type hint 其实就是把函数当静态类型来推理,一个函数只能有一种返回值,那自然就是父类类型。至于实际返回的对象是什么类型,这是另外一回事。这个 type hint 确实没错,只是它跟你的理解不太一样。
|
|
24
@InkStone 我只是看到,同样的代码,ts 里面的类型推断是正确的,但是 py 不正确,所以希望看看有没有什么方法能实现
|
|
bnm965321Apr 21, 2020
25
是 Pycharm IDE 提示不正确,还是 mypy typecheck 不正确?
|
|
chenxytwApr 21, 2020
26
@xiaoming1992 没针对你的问题啦....你这个问题我也不知道....也是进来学习的 Orz....
|
|
27
@bnm965321 vscode python 插件的智能提示
|