[英]how can i use a function for different things (don't know how else to word it)
[英]How can we make a function do different things based on the nature of its input?
我們如何在 python 中實現謂詞調度?
假設我們有一個名為 funky_the_function 的funky_the_function
。
funky_the_function
應該根據標准測試其輸入,然后根據測試結果調用其他一些 function。
以下是測試謂詞的一些示例:
class Predicates:
@classmethod
def is_numeric_string(cls, chs:str) -> bool:
"""
+-----------------+--------+
| INPUT | OUTPUT |
+-----------------+--------+
| "9821" | True |
| "3038739984" | True |
| "0" | True |
| "3.14" | False |
| "orange" | False |
| "kiwi 5 pear 0" | False |
+-----------------+--------+
"""
return all([ch in string.digits for ch in chs])
@classmethod
def is_just_one_thing(cls, thing):
"""
This function returns a boolean (True/False)
`thing` is defined to just one thing only,
not many things if str(thing)
is the same as the concatenation
of the to-stringed versions
of all of its elements
(The whole is the sum of its parts)
+--------------------------+--------+
| INPUT | OUTPUT |
|--------------------------|--------|
| int(4) | True |
| str(4) | True |
| float(9.17) | True |
| str("ABCDE") | True |
| [int(1), str(2), int(3)] | False |
| (8, 3) | False |
| [8] | False |
| ["A", "B", "C"] | False |
+--------------------------+--------+
"""
if hasattr(thing, "__iter__"):
return str(thing) == "".join(str(elem) for elem in thing)
else: # thing is not iterable
return True
我們有幾個不同版本的 function。
應該調用哪個版本的 function 取決於它的輸入。
我們如何在 python 中實現謂詞調度?
假設 funky_the_function function 有 8 個不同的funky_the_function
。
我們可以:
- 編寫
funky_the_function
的 8 種不同實現- 編寫八個不同的測試謂詞
- 寫八個不同的類。
之后我們可以編寫一個funky_the_function
function :
- 測試它的輸入。
- 根據測試結果,將輸入傳遞給幾個不同的 class 構造函數之一
- 使用 python 的
functools
庫中的@singledispatchmethod
進行調度
from functools import singledispatch
class ArgsOne:
pass
class ArgsTwo:
pass
def funky_the_function(*args):
if test_one(args):
obj = ArgsOne(args)
return _funky_the_function(obj)
elif test_two(args):
obj = ArgsTwo(args)
return _funky_the_function(obj)
@singledispatch
def _funky_the_function():
pass
@_funky_the_function.register
def _(arg:ArgsOne):
print("implementation one")
@_funky_the_function.register
def _(arg:ArgsTwo):
print("implementation one")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.