Wednesday, May 25, 2016

An Introduction to Object Oriented Programming in Python - Part 9

OOP Example: Find distance from origin

Make sure you read Part 1, Part 2, Part 3, Part 4Part 5 Part 6Part 7, and Part 8 before you continue reading...

To better understand OOP you need to lay your hands on more problem examples. In this example, lets model a formula to: Find distance from origin

In python, the formula can be expressed as: (x**2 + y**2)**0.5

Now to use OOP model the above formula, we will create a class call "Point" and defines a method "distance()" to calculate the distance from origin

class Point:
    def __init__(self, x = 0, y = 0):
        self.x = x
        self.y = y

    def distance(self):
        """Find distance from origin"""
        print (self.x**2 + self.y**2) ** 0.5

p1 = Point(6,8)

That is it.
Reference Materials are here

No comments:

Post a Comment