I want to pass a function to a function in Python. I know I can do this simply by putting the function name as a parameter, eg:
blah(5, function)
However, I want to pass the int()
function and the float()
function to this function. If I just put the function name in then it assumes I am referring to the int
and float
types not the functions for converting strings to ints and floats.
Is there a way to pass the function rather than the type?
Objects behave differently from one another according to what “type” a given object is. We reviewed several fundamental object types in Python: int , float , complex : the numerical types. bool : the boolean type.
It's always a float. It's inside the int call, though. On your second print statement: Python 3 is such that 9/2==4.5 . @Manaar // returns int if both operands are int and magnitude is always floor, Whereas / returns exact division.
Yes, python functions are full objects. They can have attributes and methods like objects. The functions can have data variables and even functions written inside of them.
In this article, we are going to see all the pre-defined functions that are available in Python. You have already used some of the Python built-in functions, for example, the print() function is used to output a string on the console. As of now, the latest version of Python 3.8 has 69 built-in functions.
Just passing int
and float
is fine. You are right that this will actually pass type objects instead of functions, but that's not important. The important thing is that the passed object is callable, and calling the type objects will do what you expect.
The type objects are what you want.
>>> def converter(value, converter_func):
... new_value = converter_func(value)
... print new_value, type(new_value)
...
>>> converter('1', int)
1 <type 'int'>
>>> converter('2.2', float)
2.2 <type 'float'>
>>>
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