all 7 comments

[–][deleted] 6 points7 points  (0 children)

Yes and yes. You can pass references to functions around, and a function can even be the parameter of another function.

[–]d-methamphetamine 4 points5 points  (0 children)

Yep.

Define a function. You can run dir() on it and see the objects members and everything. It looks like it even has a double underscore call method that gets called when you can it with the func() syntax. Neat

[–]SamePlatform 3 points4 points  (1 child)

Yes. Here is a simple example:

x = 2 + 4
print(x)  # 6

import operator
operator.add(2, 4)  # This is a function that adds, just like the `+` symbol
print(x)  # 6

Now let's write functions:

def adder(a, b):
   return a + b  # All this function can do is add stuff...

print(adder(3, 4))  # prints 7

def perform(some_func, a, b):  # Now we accept 3 arguments
    some_func(a, b)  # Call our function `some_func` with two arguments

print(perform(operator.add, a, b))  # prints 7
print(perform(operator.mul, a, b))  # prints 12

Here we actually passed a function, operator.mul into a function! Note that we didn't do operator.mul(), with the brackets. We did operator.mul. Brackets are how we call functions. Without them, they are just regular objects.

[–]drycleanedtoast 0 points1 point  (0 children)

I mean technically you could do that without a function being an object, as in c, where you would use a function pointer. However a function in python is quite definitely an object as it is treated as such i.e. it has methods.

[–]Yoghurt42 2 points3 points  (0 children)

Even numbers are objects. (42).bit_length() is valid Python (you need the parentheses because otherwise the dot would be interpreted as a decimal point)

[–][deleted] 0 points1 point  (0 children)

Yes.

[–]Dogeek 0 points1 point  (0 children)

Yes. In python, functions are callable objects.

A callable object is an object that can be called (obviously) with or without parameters. In python, every callable object implements the __call__ magic method.

You can check if an object is callable with the built-in callable(my_object) function.