9. 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 called halfway
that takes another point object as a parameter and returns a new point object that is halfway between the original point and the target.
The resulting point object, mid
, has an x value of 4 and a y value of 8. We can also use any other class methods on it, like distance_from_origin
since mid
is an object of the Point
class.