仅将参数传递给函数,如果该参数接受Python

问题描述 投票:0回答:2

我有一个'validate'方法,其工作原理如下:

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方法中?]

我有一个'validate'方法,其工作原理如下:def validate(self,allow_deferred_fields = False):“”“验证组中的数据。如果有任何不正确的数据,则引发ValidationError。...

python parameter-passing
2个回答
1
投票

这是一个设计问题。当前,validate的“合同”的一部分是它将调用带有零参数的方法custom_validation。您需要更改validate来接受其他参数以继续传递:


0
投票

在这种情况下,很难检查函数是否接受参数(请参见inspect.signature),但是如果不支持参数,很容易调用函数并捕获错误,知道函数永远不会引发TypeError

© www.soinside.com 2019 - 2024. All rights reserved.