Conversion between method and function

At this point, draw() and draw_arrow() are static methods of the Point class, and therefore can only be called using Point.draw() and Point.draw_arrow(), respectively. Let's say we'd like to convert these two methods into functions outside the scope of the Point class so that they can be called in a simpler way. To do this, we can take advantage of the intention feature that we discussed earlier in this chapter:

  1. Specifically, move your cursor to the signature of either method, wait for the Intention drop-down menu to appear, and choose Convert static method to function:

Method/function conversion via intention
  1. Do this for both methods. You should end up with them being converted into functions that are beyond the scope of the Point class. Specifically, your code should look like the following:
class Point():
...

def distance(self, p):
diff = self - p
return sqrt(diff.x ** 2 + diff.y ** 2)


def draw_arrow(bottom, left, right, top):
plt.arrow(left, 0, right - left, 0, length_includes_head=True,
head_width=0.15)
plt.arrow(0, bottom, 0, top - bottom, length_includes_head=True,
head_width=0.15)


def draw(x, y):
# set up range of the plot
limit = max(x, y) + 1

...


if __name__ == '__main__':
p1 = Point(1, 0)
p2 = Point(5, 3)

draw(p2.x, p2.y)

Notice that the call to draw() in the main scope and the one to draw_arrow() inside the draw() function itself do not involve the Point class anymore—the two are now independent functions inside our point.py script.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.183.1