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
  Int.From_Bytes Method - Conversion of Non-Escaped Bytes Objects new_coder_231013 2 384 Apr-06-2024, 04:24 PM
Last Post: new_coder_231013
  Why is the copy method name in python list copy and not `__copy__`? YouHoGeon 2 252 Apr-04-2024, 01:18 AM
Last Post: YouHoGeon
  class definition and problem with a method HerrAyas 2 234 Apr-01-2024, 03:34 PM
Last Post: HerrAyas
  Operation result class SirDonkey 6 504 Feb-25-2024, 10:53 AM
Last Post: Gribouillis
  super() and order of running method in class inheritance akbarza 7 723 Feb-04-2024, 09:35 AM
Last Post: Gribouillis
  problem usage of static method akbarza 5 533 Feb-03-2024, 07:43 AM
Last Post: paul18fr
  Building a DoublyLinkedList in Python - - append method Drone4four 2 416 Jan-08-2024, 01:27 PM
Last Post: Drone4four
Information Best distribution method inovermyhead100 0 552 Jul-19-2023, 07:39 AM
Last Post: inovermyhead100
  method call help sollarriiii 6 1,145 Feb-21-2023, 03:19 AM
Last Post: noisefloor
  That compression method is not supported tester_V 9 3,487 Jan-31-2023, 07:05 PM
Last Post: tester_V

Forum Jump:

User Panel Messages

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