Pass All Arguments Of A Function To Another Function
Solution 1:
The standard way to pass on all arguments is as @JohnColeman suggested in a comment:
classClassWithPrintFunctionAndReallyBadName:
...
defprint(self, *args, **kwargs):
if self.condition:
print(*args, **kwargs)
As parameters, *args
receives a tuple of the non-keyword (positional) arguments, and **kwargs
is a dictionary of the keyword arguments.
When calling a function with *
and **
, the former tuple is expanded as if the parameters were passed separately and the latter dictionary is expanded as if they were keyword parameters.
Solution 2:
I know it looks a bit ugly but works perfectly, if you are using a lot of keyword arguments and only want to build a facade for another method:
defprint(self, print_message, end='\n', sep=' ', flush=False, file=None):
if self.condition:
print(**{key: value for key, value inlocals().items() if key notin'self'})
Although it's a lot of boilerplate, it avoids any duplication of parameter statements.
You might also look into using a decorator to make the conditional part more pythonic. But beware that the decorator checks the condition once prior to the class instantiation.
Solution 3:
Just duplicate the named arguments for the method signature.
def print(self, *args, end='\n', sep=' ', flush=False, file=None):
ifself.condition:
print(*args, end=end, sep=sep, flush=flush, file=file)
Solution 4:
classList(list):
defappend_twice(self, *args, **kwargs):
self.append(*args, **kwargs)
self.append(*args, **kwargs)
l = List()
l.append_twice("Hello")
print(l) # ['Hello', 'Hello']
Solution 5:
Add at the end like this
defprint(self, *args, end=''):
If the arguments are dynamic or too many:
defprint(self, *args, **kwargs):
Post a Comment for "Pass All Arguments Of A Function To Another Function"