Python Forum

Full Version: Using one method's result for another method in the same Class?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey Guys,

I have a question as mentioned in the title. can you use one method's result for another method in the same Class?. I wish to use the result of the area method in the get_amount_inside method. Is there a way to do this? or put the equation for area L*W.

Thanks for your Help!

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

    def get_area(self):
        area = self.width * self.height
        return area

    def get_amount_inside(self, shape):
        self.shape = shape
        if self.shape == "sq":
            num_times = self.area/(self.width * self.width)
            return num_times
 
Sure. Normally you'll just use self to call the method. Something like:

def get_amount_inside(self):
    area = self.get_area()
    # do more stuff using the area....
get_area() is a method (function), not an attribute. So you need the parenthesis to call it.
Thanks buddy! appreciate it.
Note that you can turn get_area into property using @property decorator.

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


    @property 
    def area(self):
        return self.width * self.height

rect = Rectangle(10, 2)
print(rect.area)