Search code examples
pythonclassmethods

Is it possible to call a mehod as a variable?


I have a class: class1 It has multiple methods: method1, method2,...

is is possible to define a variable like: var = method1 to call this method from an instance of class1 ?

Meaning, instead of doing this:

instance1 = class1

result = instance1.method1

I want to do something like this:

instance1 = class1
var = method1

result = instance1.var

Is this somehow possible in python?

Many thanks upfront

I tried exactly like this:

instance1 = class1
var = method1

result = instance1.var

Solution

  • Yeah, you are just missing the parentheses, ():

    class Class1:
        def method1(self):
            return "Method1 called"
    
    instance1 = Class1()
    var = instance1.method1
    result = var()
    print(result)
    

    Output:

    Method1 called