Python Forum
Using one method's result for another method in the same Class?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using one method's result for another method in the same Class?
#1
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
 
Reply
#2
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.
Reply
#3
Thanks buddy! appreciate it.
Reply
#4
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)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  __eq__ method related problem Tsotne 6 772 Mar-09-2025, 03:48 PM
Last Post: Tsotne
  Changing client.get() method type based on size of data... dl0dth 1 546 Jan-02-2025, 08:30 PM
Last Post: dl0dth
  Error in the method "count" for tuple fff 2 777 Nov-24-2024, 03:29 AM
Last Post: fff
  Trying to understand method Giri234 1 660 Oct-04-2024, 02:10 AM
Last Post: deanhystad
  Destructor method adding in string chizzy101010 3 876 Sep-03-2024, 12:31 PM
Last Post: chizzy101010
  Difference between method and attribute holding a function ulrich 2 880 Jun-30-2024, 08:35 AM
Last Post: snippsat
  comtypes: how to provinde a list of string to a COM method zalanthas 0 882 Jun-26-2024, 01:27 PM
Last Post: zalanthas
Question No disconnect method for snowflake.connector ? Calab 0 796 Jun-11-2024, 09:42 PM
Last Post: Calab
  Which method name would you choose? Gribouillis 7 1,689 May-30-2024, 07:05 AM
Last Post: buran
  Method returning None husksedgier 2 1,081 May-04-2024, 06:38 PM
Last Post: husksedgier

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020