Pycharm 2017
低版本的 Pycharm 並不支持 Type Hint,因此這裏假設是比較新的版本。html
Python 3.5
在如今的 Python 社區,3 愈來愈成爲主流,好幾個重量級的庫/框架都不在對 2 提供支持。而 3.5 是一個比較重要的版本( 若是是新項目,通常都直接 3.5/3.6 ),因此本文使用 3.5 。編程
靜態類型很重要
因爲我並不是相關專業人士,這裏姑且這樣稱呼吧。因爲 Python 是動態語言,因此 Type Hint 與 C++/Java 那樣的靜態類型並非一回事,僅僅是 IDE 提示使用(都已經選擇了動態語言,還要啥錘子,湊合用吧 :))。好在如今大部分人都會使用 IDE 編程(指:編寫生產代碼 ),因此 Type Hint 啥的,仍是可堪一用的。bash
總之,若是把 Java/C++ 的那種比喻成火箭大炮,那Type Hint 就是打火機。左看右看,用打火機都是要比「鑽木取火」要好 :)。框架
對類型的標註,咱們可能有以下幾個方面的需求。函數
一是入參。按照參數類型分,又能夠分爲以下幾類:學習
二是出參(返回值)。基本和入參的分類一致,不在贅述。ui
下面咱們來看看,在 2 和 3 中,如何分別實現咱們上面列舉的需求。spa
Pycharm 對此有比較完備的支持,基本夠用,惟一的缺點是繁瑣。code
示例以下:htm
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
def get_name(self):
return self._name
def get_age(self):
return self._age
class Py2TypehintTester:
def test1(self, a, b, c):
"""第一種需求 基本很容易知足 :type a: str :param a: :type b: str :param b: :type c: list :param c: :rtype: list :return: """
return [a, b, c]
def test2(self, a, b, c):
"""第二種需求 也很容易知足,只不過須要遵循 Pycharm 規定的語法, 它才能正確解析 :type a: list[str] :param a: :type b: list[int] :param b: :type c: dict[str, int] :param c: :rtype: dict[str, str] :return: """
for item in a:
item.upper()
def test3(self, p):
"""第三種需求 也很容易知足. 不過須要對應的 class 在本module 的空間內( 好比, 從別處 import 進來也是能夠的) :type p: Person :param p: :return: """
age = p.get_age()
def test4(self, callback):
"""第四種需求 會讓你容易知足, 須要遵循特定寫法 :type callback: (str, int) -> str :param callback: :return: """
s = 's'
i = 1
result = callback(s, i)
print(result) # 能正確推導爲str
複製代碼
這種方式的優勢很明顯,即: 沒啥依賴,只須要遵循規定的寫法就行了。
這種方式是官方規定的,與上面一種方式比起來,基本上簡潔許多,並且也很符合直覺,可能須要一段時間適應。
示例以下:
import typing # 需求導入這個庫
# 生成複合類型, 這段代碼請無視
FloatVector = typing.List[float]
StrList = typing.List[str]
MyT = typing.TypeVar('T')
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
def get_name(self):
return self._name
def get_age(self):
return self._age
class Py3TypehintTester:
def test1(self, a: str, b: str, c: str) -> list:
"""第一種需求 很簡單, 形式比較簡潔 :param a: :param b: :param c: :return: """
return [a, b, c]
def test2(self, a: typing.List[str],
b: typing.List[str],
c: typing.Dict[str, int]) -> typing.Dict[str, str]:
"""第二種需求 比較簡單, 須要先了解 typing 這個庫 :param a: :param b: :param c: :return: """
return {
'str': 'str1'
}
def test3(self, p: Person):
"""第三種需求 比較簡單 :param p: :return: """
print(p.get_age())
def test4(self, callback: typing.Callable[[str, int], str]):
"""第四種需求 稍複雜, 須要先仔細閱讀下代碼 不過這種需求基本出現的頻率很少, 倒也不影響大局 :param callback: :return: """
s = 's'
i = 1
result = callback(s, i)
print(result) # 能推導爲str
複製代碼
if >= 3.5:
使用第二種,畢竟簡潔許多,並且也沒啥學習成本,十幾分鐘的事
要求也比較高: 對 IDE 版本和 Python 版本均有要求
else:
使用第一種,能夠視做過渡吧,反正兼容性是最好的,哪一個版本的 Pycharm 都能正確提示
複製代碼