【发布时间】:2015-09-25 17:14:35
【问题描述】:
在下面的 Python 3.5 代码中,我想使用小于运算符 (<) 来比较两个通用值。如何声明对 T 的约束以支持__lt__?
from typing import *
import operator
T = TypeVar('T')
class MyList(Generic[T]):
class Node:
def __init__(self, k:T) -> None:
self.key = k
self.next = None # type: Optional[MyList.Node]
def __init__(self) -> None:
self.root = None # type: Optional[MyList.Node]
def this_works(self, val:T) -> bool:
return self.root.key == val
def not_works(self, val:T) -> bool:
return operator.lt(self.root.key, val)
我正在使用 Mypy 进行类型检查,但在 not_works 上失败并显示以下消息:
$ mypy test.py
test.py: note: In member "not_works" of class "MyList":
test.py:20: error: Unsupported left operand type for < ("T")
其他语言支持对 T 的约束。
在 C# 中:class MyList<T> where T:IComparable<T>
在 Java 中:class MyList<T extends Comparable<? super T>>
【问题讨论】:
-
为什么人们会有用静态类型动态语言的冲动?顺便说一句,你为什么不先尝试定义
__ge__(__ge__是__lt__的右侧版本)。 "this_works" 有效,因为__eq__是为所有类定义的。 -
@JBernardo “为什么人们会有将静态类型输入动态语言的冲动?” — 因为它有很多优点。
标签: python-3.x generics types