You certainly can pass a method as a parameter to a function in Python. In my example below, I created a class (MyClass) which has two methods: isOdd and filterArray. I also created an isEven function outside of MyClass. The filterArray
takes two parameters - an array and a function that returns True or False - and uses the method passed as a parameter to filter the array.
Additionally, you can pass lambda functions as parameter, which is like creating a function on the fly without having to write a function declaration.
def isEven(num):
return num % 2 == 0
class MyClass:
def isOdd(self, num):
return not isEven(num)
def filterArray(self, arr, method):
return [item for item in arr if method(item)]
myArr = list(range(10)) # [0, 1, 2, ... 9]
myClass = MyClass()
print(myClass.filterArray(myArr, isEven))
print(myClass.filterArray(myArr, myClass.isOdd))
print(myClass.filterArray(myArr, lambda x: x % 3 == 0))
Output:
[0, 2, 4, 6, 8]
[1, 3, 5, 7, 9]
[0, 3, 6, 9]