0

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).

1
  • I dont want to call a function as a method of the class object, the function I wanna make is outside that. Commented Nov 28, 2018 at 23:31

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent. Thanks u! (ps: its a very particular case, ive to handle with too large named methods (i didnt built that) and ive to call a function which uses these methods too much time. Thanks u)
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.