Home > OS >  Can we use a variable from method of a class in another method?
Can we use a variable from method of a class in another method?

Time:03-04

class column:
    def __init__(self, length, width, height):
        self.length = length
        self.width = width
        self.height = height

    def volume(self):
        _volume = self.length*self.width*self.height **#I want to use this variable in the method below**
        print("Your result is: ")
        print(_volume)
        return self._volume

    def constituents(self):
        vol = self._volume **# here, instead of creating a new variable I want to use the previous one**
        x = int(input('ratio of cement: '))
        y = int(input('ratio of sand: '))
        z = int(input('ratio of aggregate: '))
        cement = (1.54 * (x/(x y z) * vol))
        sand = (1.54 * (y/(x y z) * vol))
        aggregate = (1.54 * (z/(x y z) * vol))
        print("The concrete consists of "   str(cement)   " cement "  
              str(sand)   " sand "   str(aggregate)   " aggregate.")

I am working in python and new to it. I want to use the volume variable (that I have defined in the function volume), in the function constituents. Now if I do the simple return thing, it gives unsupported operand type(s) for *: 'float' and 'method' error. If I use parenthesis while returning the variable, it gives the RecursionError: maximum recursion depth exceeded while calling a Python object error.
So, I just wanted to ask if it is possible to do so. If not what is a possible solution, without creating another variable.

CodePudding user response:

_volume =/= self._volume - if you want a variable shared between methods of an object (like __init__, volume and constituent s), you need to add them to the self. object. You never assign anything to self._volume

CodePudding user response:

If I understood you correctly, you want to use volume() to set your self._volume property. Therefore you can change your volume() method to

def volume(self):
    self._volume = self.length*self.width*self.height **#I want to use this variable in the method below**
    print("Your result is: ")
    print(self._volume)
    return self._volume

Note that the return self._volume line is optional since self._volume is now accessible throughout your object.

This is basically what khelwood and matszwecja have pointed out as well.

  • Related