Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass all arguments of a function to another function

Tags:

python

I want to have a class that I can create subclasses of that has a print function that only prints on a particular condition.

Here's basically what I'm trying to do:

class ClassWithPrintFunctionAndReallyBadName:
    ...
    def print(self, *args):
        if self.condition:
            print(*args)

This works already except for the fact that there are arguments that have to be explicitly stated with the default print function, such as end (example: print('Hello, world!', end='')). How can I make my new class's print function accept arguments such as end='' and pass them to the default print?

like image 973
Neithan Avatar asked Feb 28 '17 03:02

Neithan


People also ask

Can you pass a function as an argument to another function?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.

Can you pass a function as an argument to another function in Python?

Summary. In Python you can pass function objects in to other functions. Functions can be passed around in Python. In fact there are functions built into Python that expect functions to be given as one or more of their arguments so that they can then call them later.

Which variable contains all the arguments passed to a function?

arguments is an Array -like object accessible inside functions that contains the values of the arguments passed to that function.

How do you pass multiple parameters to a function?

Note that when you are working with multiple parameters, the function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.


2 Answers

The standard way to pass on all arguments is as @JohnColeman suggested in a comment:

class ClassWithPrintFunctionAndReallyBadName:
    ...
    def print(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.

like image 92
Mark Tolonen Avatar answered Oct 26 '22 01:10

Mark Tolonen


class List(list):
    def append_twice(self, *args, **kwargs):
        self.append(*args, **kwargs)
        self.append(*args, **kwargs)
l = List()
l.append_twice("Hello")
print(l) # ['Hello', 'Hello']
like image 38
Steely Wing Avatar answered Oct 26 '22 02:10

Steely Wing