【发布时间】:2017-12-03 19:53:07
【问题描述】:
假设我有以下课程:
class Parent:
def clone_self(self) -> 'Parent':
clone = self.__class__()
# Initialize clone here.
return clone
def clone_with_class(self, klass: Type['Parent']) -> 'Parent':
clone = klass()
# Initialize clone here.
return clone
class Child(Parent):
def child_method(self) -> None:
pass
有什么方法可以让类型更具体吗?我希望能够说:
child = Child()
clone = child.clone_self()
clone.child_method()
clone = child.clone_with_class(Child)
clone.child_method()
但是,正如所写,这不会通过类型检查,因为克隆被认为是Parent 类型而不是Child。
我尝试使用TypeVar,但这似乎不起作用 - 至少在 PyCharm 中,因为当我尝试调用构造函数时它抱怨该类型不可调用,可能是因为它涉及前向引用,而 PyCharm 是迷糊了。
Entity = TypeVar('Entity', bound='Parent')
class Parent:
def clone_self(self) -> ???:
clone = self.__class__()
# initialize clone here
return clone
def clone_with_class(self, klass: Type[Entity]) -> Entity:
clone = klass()
# initialize clone here
return clone
clone_with_class 的解决方案是否正确?也许 PyCharm 是错误的抱怨?否则,需要做什么来修复上面的代码?
应该是TypeVar('Entity', bound='Parent') 还是TypeVar('Entity', 'Parent')?
我发现的另一个解决方案是插入断言,虽然看起来有些难看:
child = Child()
parent = Parent()
clone = child.clone_self()
clone.child_method() # should work
clone = child.clone_with_class(Child)
clone.child_method() # should work
clone = parent.clone_with_class(Child)
clone.child_method() # should work
clone2 = parent.clone_self()
clone2.child_method() # should be an error
clone2 = parent.clone_with_class(Parent)
clone2.child_method() # should be an error
clone2 = child.clone_with_class(Parent)
clone2.child_method() # Should be an error
一旦我很好地理解了什么是正确的,我就可以在 PyCharm 错误地抱怨时向它提交错误。
根据建议的答案,我尝试使用 mypy:
from typing import TypeVar, Type
Entity = TypeVar('Entity', bound='Parent')
class Parent:
def clone_self(self: Entity) -> Entity:
clone = type(self)()
# initialize clone here
return clone
def clone_with_class(self, klass: Type[Entity]) -> Entity:
clone = klass()
# initialize clone here
return clone
class Child(Parent):
def child_method(self) -> None:
print("Calling child method")
child = Child()
parent = Parent()
clone = child.clone_self()
clone.child_method() # should work
clone = child.clone_with_class(Child)
clone.child_method() # should work
clone = parent.clone_with_class(Child)
clone.child_method() # should work
clone2 = parent.clone_self()
clone2.child_method() # should be an error
clone2 = parent.clone_with_class(Parent)
clone2.child_method() # should be an error
clone2 = child.clone_with_class(Parent)
clone2.child_method() # Should be an error
我得到以下信息:
$ mypy --strict test.py
test.py:32: error: "Parent" has no attribute "child_method"
test.py:35: error: "Parent" has no attribute "child_method"
test.py:38: error: "Parent" has no attribute "child_method"
这些错误是预期的。
【问题讨论】:
-
我添加了更多测试用例来测试所需的行为。
标签: python python-3.x python-3.5 type-hinting