Home > Blockchain >  in class, pass from method to method the values of local variables
in class, pass from method to method the values of local variables

Time:06-28

I have a problem to pass from method to method the values of local variables. I didn't put them in the constructor because I would like some processing to be done in the methods

class Myclass:
    
    def __init__(self,nbr1,nbr2):
        self.nbr1 = nbr1
        self.nbr2 = nbr2
        
    def operation1(self):
        nbr3 =nbr1 nbr2
        return nbr3
        
 #I would like to pass the nbr3 value in the operation2 function
# for some treatments       
        
    def operation2(self):
        nbr4= nbr3*2
        return nbr4, nbr3 
        
 #and return value of def operation2 in showMe function       
    def showMe(self,param):
        showresult = param()
        print(f'this a result : {showresult[0]} and another result {showresult[1]}')

nbr1 = 5
nbr2 = 7

result = Myclass(nbr1,nbr2)

result.showMe(result.operation2)

but I have an error nbr3 is not defined

thank for helps

CodePudding user response:

You need to actually call operation1() somewhere

def operation2(self):
    nbr3 = self.operation1()
    nbr3 *= 2
    return nbr4, nbr3 

Or set the instance variable

def operation1(self):
    self.nbr3 = self.nbr1   self.nbr2

def operation2(self):
    nbr4 = self.nbr3 * 2
    return nbr4, self.nbr3 

...

result = Myclass(nbr1,nbr2)
result.operation1()
result.showMe(result.operation2)

Or remove the operation1 and set the instance variable

class Myclass:
    
    def __init__(self,nbr1,nbr2):
        self.nbr1 = nbr1
        self.nbr2 = nbr2
        self.nbr3 = self.nbr1   self.nbr2
        
    def operation2(self):
        nbr4= self.nbr3 * 2
        return nbr4, nbr3 
  • Related