Python ellipsis 的用法詳解
阿新 • • 發佈:2020-11-24
背景
在 Python 的基本型別中單例模式的值有三個 None 型別的 None,NotImplemented 型別的 NotImplemented,Ellipsis 型別的 ... 。
None 已經用的爛大街了,NotImplemented 也比較常用,唯獨 ... 在江湖上只知它是三巨頭之一,但不知其用法。
Ellipsis
Ellipsis 在 python 中代表“省略”,用現在的流形語來表達就是“老鐵,不要在意這些細節!”。哪什麼時候要告訴別人不要在意這些細節呢?其中的一個場景就是隨機值。
用於文件測試
假設我們編寫了一個類,要想知道這個有沒有語法層面的錯誤,只要簡單的呼叫一下就能測試出來。為了把這個測試自動化,於是做成了文件測試。
#!/usr/bin/evn python3 class Person(object): """人類型別 Parameters: ---------- name: str age: int Return: ------ >>> Person() <main.Person object at 0x7ff36c1ca250> """ name = '' age = 0 def __init__(self,name: str = 'tom',age: int = 10) -> 'Person': """初始化 """ self.name = name self.age = age def say_hello(self) -> str: """返回打招呼資訊 """ return f"Hello My name is {self.name} ."
當我們執行測試用例時會報錯,原因是每次建立的物件,它的記憶體地址並不等於測試用例中指定的哪個,而我們的用例上寫死了。誠然這個問題用 unittest 可以解決,但是這個不是這裡要講的。
python3 -m doctest main.py -v Trying: Person() Expecting: <main.Person object at 0x7ff36c1ca250> ********************************************************************** File "/private/tmp/main.py",line 12,in main.Person Failed example: Person() Expected: <main.Person object at 0x7ff36c1ca250> Got: <main.Person object at 0x7fe4e078ac70> 3 items had no tests: main main.Person.__init__ main.Person.say_hello ********************************************************************** 1 items had failures: 1 of 1 in main.Person 1 tests in 4 items. 0 passed and 1 failed. ***Test Failed*** 1 failures.
哪如何才能告訴 doctest 這位老鐵不要在意返回值細節呢?答案是加上 Ellipsis 這個指令,改造後的程式碼如下。
#!/usr/bin/evn python3 class Person(object): """人類型別 Parameters: ---------- name: str age: int Return: ------ >>> Person() #doctest: +ELLIPSIS <main.Person object at 0x...> """ name = '' age = 0 def __init__(self,age: int = 10) -> 'Person': """初始化 """ self.name = name self.age = age def say_hello(self) -> str: """返回打招呼資訊 """ return f"Hello My name is {self.name} ."
執行測試用例這下可以通過了。
python3 -m doctest main.py -v Trying: Person() #doctest: +ELLIPSIS Expecting: <main.Person object at 0x...> ok 3 items had no tests: main main.Person.__init__ main.Person.say_hello 1 items passed all tests: 1 tests in main.Person 1 tests in 4 items. 1 passed and 0 failed. Test passed.
其它
如果我們是為模組新增測試用例,那麼可以這樣做,會方便一些。
#!/usr/bin/evn python3 class Person(object): """人類型別 Parameters: ---------- name: str age: int Return ------ >>> Person() #doctest: +ELLIPSIS <...Person object at 0x...> """ name = '' age = 0 def __init__(self,age: int = 10) -> 'Person': """初始化 """ self.name = name self.age = age def say_hello(self) -> str: """返回打招呼資訊 """ return f"Hello My name is {self.name} ." if __name__ == "__main__": # 因為在模組在被 import 的時候 __name__ 直接等於 模組名 不等於 “__main__” ,所以在作為模組被匯入時並不會執行測試用例 # 如果想執行測試用例直接執行模組就行 import doctest doctest.testmod()
以上就是Python ellipsis 的用法詳解的詳細內容,更多關於Python ellipsis的資料請關注我們其它相關文章!