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).
-
I dont want to call a function as a method of the class object, the function I wanna make is outside that.sebach1– sebach12018年11月28日 23:31:41 +00:00Commented Nov 28, 2018 at 23:31
2 Answers 2
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.
1 Comment
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]