仅在函数接受该参数时才将参数传递给函数 Python

我有一个“验证”方法,其工作方式如下:


def validate(self, allow_deferred_fields=False):

    """

    Validate the data in the group.

    Raises ValidationError if there is any incorrect data.

    """

    # Check custom validation of current group

    self.custom_validation()

custom_validation 方法因验证的组而异。我的 custom_validation 定义之一我想像这样传递参数“allow_deferred_fields”:


def custom_validation(self, allow_deferred_fields=False):

    if allow_deferred_fields:

    .... some code

但其他 custom_validation 方法不采用此参数。如何将此参数传递到 validate 方法中的 custom_validation 调用中,而不必将其作为参数添加到它可能调用的所有其他 custom_validation 方法中?


猛跑小猪
浏览 104回答 2
2回答

米琪卡哇伊

这是一个设计问题。目前,validate的“合同”的一部分是它将调用一个custom_validation参数为零的方法。您需要更改validate以接受要传递的其他参数:def validate(self, *args, **kwargs):    self.custom_validation(*args, **kwargs)或者您需要将标志“嵌入”到对象本身中,以便custom_validation在调用时可以访问它。def validate(self):    self.custom_validation()def custom_validation(self):    if self.allow_deferred_fields:        ......obj.allow_deferred_fields = Trueobj.validate()不过,第二个选项有点麻烦。这并不比有一个全局变量来custom_validation检查好多少。第三个选项是强制所有自定义验证方法在被 调用时接受(可能是任意的)关键字参数validate,尽管它们可以自由地忽略该参数。

慕仙森

在这种情况下,很难检查函数是否接受参数(请参阅 inspect.signature),但调用函数并在函数不支持参数时捕获错误非常容易,前提是您知道函数将永远不要引发 TypeError。这样做的好处是还可以使用基于 C 的函数。def validate(self, allow_deferred_fields=False):    """    Validate the data in the group.    Raises ValidationError if there is any incorrect data.    """    # Check custom validation of current group    try:        self.custom_validation(allow_deferred_fields=True)    except TypeError:        self.custom_validation()如果你不能依赖函数永远不会抛出 TypeError,你可以尝试以下方法,但请记住,如果函数是用 C 实现的,它将失败def validate(self, allow_deferred_fields=False):    """    Validate the data in the group.    Raises ValidationError if there is any incorrect data.    """    # Check custom validation of current group    if "allow_deferred_fields" in inspect.signature(self.custom_validation):        self.custom_validation(allow_deferred_fields=True)    else:        self.custom_validation()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python