20.8. 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. (You can also have lists or tuples of object instances, etc.) 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, let’s call it halfway, which takes another Point as a parameter and returns the Point that is halfway between the point and the target point it accepts as input.

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

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

You have attempted 1 of 2 activities on this page