[英]Check if function passed as argument to class __init__ returns right type
我正在嘗試設置一個 class 來概括一些數值模擬,問題的核心如下:
假設我有一個 function 返回numpy.ndarray
類型,比如
def new_fun():
return numpy.zeros((2,2,2,2))
然后我有一個 class 聲明,如:
class NewClass:
def __init__(self,function):
self.function = function
我的目標:如果傳遞給__init__
的參數是 function 並返回正確的類型,我想檢查 class 初始化,例如:
class NewClass:
def __init__(self,function):
if type(function) is types.FunctionType:
#from here is pseudocode
if return_type(function) is numpy.ndarray:
self.function = function
重要的是:鑒於應用程序的類型,不得執行傳遞的 function 以獲取有關返回類型的信息,這可能需要一段時間。
檢查它是否可調用
def __init__(self, fn):
assert callable(fn)
知道某些函數將返回什么是不切實際的,但是您可以使用類型提示來解決這個問題
from typing import Callable
...
def __init__(self, fn: Callable[[None], numpy.ndarray]):
if not callable(fn):
raise TypeError("expected a callable function, but got {type(fn)}")
Python 的一個很大的好處是它易於閱讀和編寫——在大多數情況下,防止用戶濫用你的 API 是不切實際或沒有幫助的,但你應該努力通過良好的文檔字符串、注釋和類型來幫助他們正確使用它暗示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.