Skip to main content

Section 13.11 Instances as Return Values

Functions and methods can return objects. This is actually nothing new since everything in Python is an object, and we have been returning values for quite some time. The difference here is that we want to have a method create an object using the constructor and then return it as the value of the method.
Suppose you have a rectangle object and wish to find a rectangle large enough to enclose both it and some other rectangle. We would like to write a method named max_rect that takes another Rectangle as a parameter and returns the Rectangle whose width and height are the maximum values of the two rectangles. For example, if one rectangle has width 3 and height 8, and the other has width 15 and height 4, the maxRect will have width 15 and height 8.
The resulting Rectangle, r3, has a width of 15 and height of 8. Because r3 is also a Rectangle, we could print its diagonal by calling print(r3.diagonal_length()). Try putting the line into the program and see that it works.
In the definition of the method max_rect, see how the requirement to always use dot notation with attributes disambiguates the meaning of the attributes width and height: We can always see whether the dimensions of the self or other rectangle are being referred to.

Note 13.11.1.

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.