为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

猛跑小猪 2023-01-04 16:22:15
我有一个“验证”方法,其工作方式如下: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 方法中?
查看完整描述

2 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

这是一个设计问题。目前,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 = True

obj.validate()

不过,第二个选项有点麻烦。这并不比有一个全局变量来custom_validation检查好多少。


第三个选项是强制所有自定义验证方法在被 调用时接受(可能是任意的)关键字参数validate,尽管它们可以自由地忽略该参数。


查看完整回答
反对 回复 2023-01-04
?
慕仙森

TA贡献1827条经验 获得超7个赞

在这种情况下,很难检查函数是否接受参数(请参阅 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()


查看完整回答
反对 回复 2023-01-04
  • 2 回答
  • 0 关注
  • 102 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信