简体   繁体   中英

Define Method with unknown number of arguments not equal to None

I am working in Python 3.7.

Assume I have these two functions, and I cannot change their code (ie set default arguments such as 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 ? 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 ? Moreover, I do not want to create two different classes for each function type and only method function 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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