user1427026
user1427026

Reputation: 879

Reusing code from a method which performs a flag check

I have a method which calls a few other methods based on a flag..

def methodA(self):
    if doc['flag']:
         self.method1()      
         self.method2()

Now, i have to make a call to the methodA() from another place which needs to do essentially the same things, but independent of doc['flag'] (call self.method1() and self.method2() regardless of whether flag is true or false) Is there a nice way to do this?

Thanks

Upvotes: 1

Views: 87

Answers (1)

karthikr
karthikr

Reputation: 99640

One way you can do it is:

def methodA(self):
    if doc['flag']:
        self.anotherMethod()

def anotherMethod(self):
    self.method1()      
    self.method2()

Or:

def methodB(self, flag=False, execute_anyways=False):
    if not flag and not execute_anyways:
        return #Note that while calling, you would be sending True, or False. If flag=None, it would execute. 
    self.method1()      
    self.method2()

def methodA(self):
    self.methodB(flag=doc['flag'])

And in the other instance, just call

self.methodB(execute_anyways=True) #Now, the flag would have the default value of None, and would execute. 

Upvotes: 2

Related Questions