Home > OS >  Python: Assigning class method to a variable
Python: Assigning class method to a variable

Time:04-16

I have a number of methods in a class and I need to call a specific one. I tried something like this, but got an AttributeError

class MyClass:
    def first(a, b):
        return a   b
    def second(a, b):
        return a * b

a = 2
b = 3

first_func = MyClass.first
second_func = MyClass.second

my_obj = MyClass()

I expect something of a following to work, but I'm getting this exception:

my_obj.first_func(a, b)   my_obj.second_func(a, b) == 11

So is there a way to do it?

CodePudding user response:

Since your methods do not have self parameters, they are "static" and do not depend on the intantiated object. You can call your functions this way:

first_func(a, b)  # no my_obj

If in reality they do depend on the object, you would write:

class MyClass:
    def first(self, a, b):
        return a   b
    def second(self, a, b):
        return a * b

And they you can call the method "on" an object:

my_obj = MyClass()
my_obj.first(a, b)

Or, with your initial notation:

first_func = MyClass.first
first_func(my_obj, a, b)

(same for your second method)

CodePudding user response:

Function definition in a class should contain 'self' as a param

class MyClass:
    def first(self,a, b):
        return a   b
    def second(self,a, b):
        return a * b

a = 2
b = 3

first_func = MyClass.first
second_func = MyClass.second

my_obj = MyClass()
first_func(my_obj,a, b)   second_func(my_obj,a, b) == 11
  • Related