0

I have a class, and that class has two methods. Depending on the value of a variable, I want to be able to access one of those two methods. If I have multiple instances of this class, is there a way I can specify the method I want to use that will work with all the classes. For example,

class MyClass:

    def __init__(self, my_constant = 1):
        self.my_con = my_constant

    def method_1(self):
        statement = f"This is method 1 and my constant is {self.my_con}"
        return statement

    def method_2(self):
        statement = f"This is method 2 and my constant is {self.my_con}"
        return statement

I want to access the same method for all the classes, so I don't need to worry about the method changing at all. So one way would be to just have an if statement, and duplicate the code twice. Ideally I'd like to be able to avoid that and just have something that would work as follows:

my_param = True
my_method = method_1 if my_param else method_2
class_1 = MyClass(1)
class_2 = MyClass(2)
class_3 = MyClass(3)
my_statement_1 = class_1.my_method()
my_statement_2 = class_2.my_method()
my_statement_3 = class_3.my_method()

Is there a way I can do this?

user112495
  • 184
  • 9
  • You can use a string to specify the name of the method to call and use that name on each of your instances. – quamrana Sep 21 '22 at 09:18
  • @quamrana This sounds like what I want, but how can I use a string to access the method (apologies if this is an obvious question - I'm still getting my head round a lot of this stuff) – user112495 Sep 21 '22 at 09:19
  • 1
    See the duplicate above. You could also do `mm = MyClass.method_1 if .. else MyClass.method_2; mm(class_1); mm(class_2)`… – deceze Sep 21 '22 at 09:21

0 Answers0