Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Assigning class method to a variable

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading