Home > other >  How can I call any method inside a class depending on an input to another method in the same class?
How can I call any method inside a class depending on an input to another method in the same class?

Time:04-29

I am trying to call a particular method defined inside a class. This calling, however, is dependent on the input of an another method in the same class.

class my_class:
    def __init__(self, x):
        self.exam_score = x

    def math(self):
        print("Hello World!")

    def history(self):
        return "The top score is 12 out of {}.".format(self.exam_score)

    def subject_score(self, func):
        # Call either 'math' method or 'history' method based on input 'func'
        self.__getattribute__(func)()

my_class(30).subject_score('math')

Here, I am trying to call the method math of class my_class by passing math as an argument to subject_score method.

Running the above code will give out Hello World! as the output.

But is there any better way to do this than using self.__getattribute__(func)()?

Thanks!

CodePudding user response:

In the subject_score(), you have to return the attribute like this:

class my_class:
    ...

    def subject_score(self, func):
        # Call either 'math' method or 'history' method based on input 'func'
        return self.__getattribute__(func)()

my_class(30).subject_score('math')

Then you will found the result.

  • Related