我想限制可以作為引數傳遞給另一個函式的函式的范圍。例如,將功能限制為僅指定的兩個或特定模塊中的一個。我嘗試了下面的代碼,但現在有限制:作為引數可以傳遞任何函式。
這在 Python 中可能嗎?
def func_as_param():
print("func_as_param called")
def other_func():
print("other_func called")
def func_with_func_arg(func: func_as_param): # this is not giving restrictions
# def func_with_func_arg(func: type(func_as_param)): # this is also not giving restrictions
print("func_with_func_arg called")
func()
def test_func_with_func_arg():
print("test_func_with_func_arg")
func_with_func_arg(func_as_param)
func_with_func_arg(other_func) # <- here IDE must complain that only func_as_param is expected
uj5u.com熱心網友回復:
期望特定簽名的回呼函式的框架可能會使用型別提示
Callable[[Arg1Type, Arg2Type], ReturnType]
您可能想要使用 Callable 型別。這可能有助于https://docs.python.org/3/library/typing.html#callable
注意
Python 中的型別注釋不像 C 中那樣成敗。它們是可選的語法塊,我們可以添加它們以使我們的代碼更加明確。錯誤的型別注解只會在我們的代碼編輯器中突出顯示不正確的注解——不會因為注解而引發錯誤。如有必要,您必須自己進行檢查。
uj5u.com熱心網友回復:
通常這是通過創建您自己的型別(類)來完成的......然后任何其他函式都可以從它繼承并且將具有相同的“型別”。
class my_functions:
pass
class func_as_param_class(my_functions):
@staticmethod
def __call__():
print("func_as_param called")
func_as_param = func_as_param_class() # create the callable function ....
def other_func():
print("other_func called")
def func_with_func_arg(func: my_functions): # only my_functions are accepted.
# def func_with_func_arg(func: type(func_as_param)):
print("func_with_func_arg called")
func()
def test_func_with_func_arg():
print("test_func_with_func_arg")
func_with_func_arg(func_as_param)
func_with_func_arg(other_func) # <- here IDE must complain that only func_as_param is expected
在上面的代碼中,我的 IDE (pycharm) 確實抱怨other_func型別錯誤,但這在運行時沒有任何限制,它只允許 IDE linter 和 mypy 發出違規警告。
編輯:通過將呼叫函式宣告為靜態來洗掉引數。
uj5u.com熱心網友回復:
不知道是不是只有我一個人Python沒有對型別注解做任何改動
句法 :
def greeting(name: str) -> str:
return 'Hello ' name
你可以在這里找到更多:https ://docs.python.org/3/library/typing.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511200.html
標籤:Python仿制药参数
上一篇:在Golang中,如何將介面作為泛型型別與nil進行比較?
下一篇:呼叫具有匹配泛型引數的泛型函式
