简体   繁体   English

定义方法的参数数目未知,不等于None

[英]Define Method with unknown number of arguments not equal to None

I am working in Python 3.7. 我正在使用Python 3.7。

Assume I have these two functions, and I cannot change their code (ie set default arguments such as x=None ). 假设我具有这两个函数,并且无法更改它们的代码(即设置默认参数,例如x=None )。

def f1(x):
    return x

def f2(x,y):
    return x+y

Assume I have a class like this. 假设我有一堂这样的课。

class test():
    def __init__(self, var1, var2 = None, func):
        self.var1 = var1
        self.var2 = var2
        self.func = func

    def apply_func(self):
        return self.func(self.var1, self.var2)

How do I structure the definition of the class test , such that self.var2 is only passed when var2 is not None ? 如何构造类test的定义,以使self.var2仅在var2 is not None时通过? Such that I do not get an argument (too many arguments) error if I instantiate with the attribute fun1 and call the method apply_func ? 这样,如果我使用属性fun1实例化并调用方法apply_func ,就不会出现参数错误(参数过多)的apply_func Moreover, I do not want to create two different classes for each function type and only method function apply_func . 而且,我不想为每种函数类型创建两个不同的类,而只apply_func方法函数apply_func

You can slice the argument list according to the function object's __code__.argcount attribute, which stores the number of arguments expected by the function: 您可以根据函数对象的__code__.argcount属性对参数列表进行切片,该属性存储函数期望的参数数量:

def f1(x):
    return x

def f2(x,y):
    return x+y

class test():
    def __init__(self, func, var1, var2 = None):
        self.var1 = var1
        self.var2 = var2
        self.func = func

    def apply_func(self):
        return self.func(*(self.var1, self.var2)[:self.func.__code__.co_argcount])

so that: 以便:

print(test(f1, 1).apply_func())
print(test(f2, 1, 2).apply_func())

outputs: 输出:

1
3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM