11.7. 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 the method create an object using the constructor and then return it as the value of the method.

Suppose you have a point object and wish to find the midpoint halfway between it and some other target point. We would like to write a method, call it halfway that takes another Point as a parameter and returns the Point that is halfway between the point and the target.

The resulting Point, mid, has an x value of 4.0 and a y value of 8.0. We can also use any other methods since mid is a Point object.

In the definition of the method halfway see how the requirement to always use dot notation with attributes disambiguates the meaning of the attributes x and y: We can always see whether the coordinates of Point self or target are being referred to.

You have attempted of activities on this page
11.6. Converting an Object to a String"> 11.8. Glossary">Next Section - 11.8. Glossary