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
?
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.
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.
arguments is an Array -like object accessible inside functions that contains the values of the arguments passed to that 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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With