Reputation: 117
Can I pass a method as a parameter on python? I want to do things like, for example, if anything is an instance of an object w/has foo method:
def access_to(class=anything, method="foo"):
return class.method
(Note is obvious that Anything instance doesn't have the attribute 'method', and Ill get an AttributeError).
Upvotes: 0
Views: 139
Reputation: 3712
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]
Upvotes: 0
Reputation: 5016
Uses getattr if you want to get the method from a string parameter.
class A:
def foo(self):
print("foo")
def access_to(c, method="foo"):
return getattr(c, method)
a = A()
b = 5
access_to(a)()
access_to(b)()
It prints foo for a, then it raises error for b
I have to say that I recommend not to abuse this type of functions unless you have to for some specific reasons.
Upvotes: 4