-1

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
DiBiDa
  • 9
  • 3

3 Answers3

0

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
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
0

You can achieve this using Python's built-in getattr() function. getattr() allows you to access an object's attribute (including methods) using a string that contains the attribute's name. Here is an example.

class class1:

    def method1(self):
        return "This is method1's result"

    def method2(self):
        return "This is method2's result"

instance1 = class1()

var = "method1"
result = getattr(instance1, var)()

print(result)  # Output: This is method1's result

Keep in mind that this can make your code less readable.

0

You were not far, but you have to scope the variable inside the class1 class, because method1 only makes sense there:

Example:

class class1:
    def method1(self):
        print('method1 called on', str(class1), id(self))

You can test it that way:

instance1 = class1()
print(id(instance1))    # gives for example 1565329136688

class1.var = class1.method1
instance1.var()

would display:

method1 called on <class '__main__.class1'> 1565329136688
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252