[英]Python: How do you specify the parameter type of a Class function to the current class?
[英]How to specify type for function parameter (Python)
我想限制 scope 可以作為參數傳遞給另一個 function 的函數。例如,將函數限制為僅來自兩個指定的函數,或來自特定模塊,或通過簽名。 我嘗試了下面的代碼,但其中現在有限制:作為參數可以傳遞任何 function。
這在 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
通常這是通過創建您自己的類型(類)來完成的...然后任何其他 function 都可以從它繼承並且將具有相同的“類型”。
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 發出違規警告。
編輯:通過將調用 function 聲明為 static 來刪除 arguments。
期望特定簽名的回調函數的框架可能會使用
Callable[[Arg1Type, Arg2Type], ReturnType]
進行類型提示
您可能想要使用 Callable 類型。 這可能有助於https://docs.python.org/3/library/typing.html#callable
筆記
Python 中的類型注釋不像 C 中那樣成敗。它們是可選的語法塊,我們可以添加它們以使我們的代碼更明確。 錯誤的類型注解只會在我們的代碼編輯器中突出顯示不正確的注解——不會因為注解而引發任何錯誤。 如果那是必要的,你必須自己做檢查。
不知道是不是只有我一個 Python 沒有對類型 Annotations 做任何修改
句法:
def greeting(name: str) -> str:
return 'Hello ' + name
你可以在這里找到更多: https://docs.python.org/3/library/typing.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.