# First time working with Python and OOP

Page 1 of 1

## 13 Replies - 1070 Views - Last Post: 27 January 2016 - 02:05 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=387700&amp;s=74b00f2e93c9b0d4cf51e0021d403df6&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 pigeonwiki

Reputation: 0
• Posts: 4
• Joined: 22-January 16

# First time working with Python and OOP

Posted 22 January 2016 - 09:22 PM

I am new to the world of object-oriented and in Python. This is my first object-oriented application. I created a Python script that solves step by step the distance formula. Any comments on how I built this code would be very helpful.

Thank you! />

```#Python#

class distanceFormula():

def __init__(self, x2, x1, y2, y1, d = '0'):
self._x1 = x1
self._x2 = x2
self._y1 = y1
self._y2 = y2
self._d = d

def displayFormula(self):
print('Distance Formula:')
print('    d = ((x2 - x1)^2 + (y2 - y1)^2)^1/2 \n')

def execFormula(self):
print('d = (({} - {})^2 + ({} - {})^2)^1/2'.format(self._x2, self._x1, self._y2, self._y1))
x = self._x2 - self._x1
y = self._y2 - self._y1

print('d = (({})^2 + ({})^2)^1/2'.format(x, y))
x = x ** 2
y = y ** 2

print('d = ({} + {})^1/2'.format(x, y))
self._d = x + y

print('d = ({})^1/2'.format(self._d))
self._d = self._d ** .5

print('d = {}'.format(self._d))

def resultFormula(self):
return self._d

def main():

x2 = int((input('Enter a value for x2: ')))
x1 = int((input('Enter a value for x1: ')))
y1 = int((input('Enter a value for y2: ')))
y2 = int((input('Enter a value for y1: ')))
print('')

f = distanceFormula(x2, x1, y2, y1)
f.displayFormula()
f.execFormula()
print('')

x2 = int((input('Enter a value for x2: ')))
x1 = int((input('Enter a value for x1: ')))
y1 = int((input('Enter a value for y2: ')))
y2 = int((input('Enter a value for y1: ')))
print('')

e = distanceFormula(x2, x1, y2, y1)
e.execFormula()

print('')
print(f.resultFormula())
print(e.resultFormula())

if __name__ == "__main__": main()

```

Is This A Good Question/Topic? 0

## Replies To: First time working with Python and OOP

### #2 andrewsw

Reputation: 6667
• Posts: 27,299
• Joined: 12-December 12

## Re: First time working with Python and OOP

Posted 22 January 2016 - 10:15 PM

How did you build it? Describe what you did.

### #3 jon.kiparsky

• Beginner

Reputation: 11374
• Posts: 19,406
• Joined: 19-March 11

## Re: First time working with Python and OOP

Posted 22 January 2016 - 10:19 PM

I'd be curious to know what you think of it, first of all. What do you like about it, and what do you think you'd like to improve about it? These intuitions are important, you might as well start developing them.

### #4 baavgai

• Dreaming Coder

Reputation: 7361
• Posts: 15,284
• Joined: 16-October 07

## Re: First time working with Python and OOP

Posted 23 January 2016 - 02:35 AM

This looks like a bug, I'm afraid:
```y1 = int((input('Enter a value for y2: ')))
y2 = int((input('Enter a value for y1: ')))

```

I'm not sure why you ask for y2 before y1 in any case. The order seems confusing, perhaps even to you.

Also, since you do it twice ( and pasted the bug twice ) you might consider asking for values in a function.

### #5 DK3250

• Pythonian

Reputation: 499
• Posts: 1,562
• Joined: 27-December 13

## Re: First time working with Python and OOP

Posted 23 January 2016 - 02:46 AM

Hi, Nice start.
One direct failure: In line 40/41 and 51/52 you switch y1 and y2 in the input statement. This leads to switched output in line 17 (not in line with text from line 14). EDIT: Same input as baavgai, posts crossing.

I wonder why you choose 'distanceformula' as object. I would make two objects: Point and Distance. To create a Point instance you supply an x- and a y-value. To create a Distance instance you supply any two Point instances. I think your code will be more flexible this way.

If you follow my input you will need to change your main; the existing main holds a lot of repeating code, try make it into a loop.

This post has been edited by DK3250: 23 January 2016 - 02:49 AM

### #6 pigeonwiki

Reputation: 0
• Posts: 4
• Joined: 22-January 16

## Re: First time working with Python and OOP

Posted 24 January 2016 - 08:14 PM

That was a typo in lines 40-41 and 51-52. I made the corrections. Thank you!

This is a new version of the code as DK3250 commented in previous post. In the first version I used the formula as an object because I can used it to create new instances for resolve math problems. But this point of view it's very interesting. This is a practice exercise that I builded for a better understanding of the OOP.

```#!/usr/bin/python3

class Point():
def __init__(self, x2, x1, y2, y1):
self._x2 = x2
self._x1 = x1
self._y2 = y2
self._y1 = y1

class Distance():
def execFormula(self, Point):
print('d = (({} - {})^2 + ({} - {})^2)^1/2'.format(Point._x2, Point._x1, Point._y2, Point._y1))
x = Point._x2 - Point._x1
y = Point._y2 - Point._y1

print('d = (({})^2 + ({})^2)^1/2'.format(x, y))
x = x ** 2
y = y ** 2

print('d = ({} + {})^1/2'.format(x, y))
d = x + y

print('d = ({})^1/2'.format(d))
d = d ** .5

print('d = {}'.format(d))
return d

def main():

p = Point(2, 3, 7, 0)
d = Distance()
d.execFormula(p)

if __name__ == "__main__": main()

```

One question: How can I do a loop for input variables? Because I could not find a way to create it in Python.

### #7 astonecipher

• Senior Systems Engineer

Reputation: 2706
• Posts: 10,802
• Joined: 03-December 12

## Re: First time working with Python and OOP

Posted 24 January 2016 - 09:07 PM

Did you see how you would take input?

```val = input('>')
```

To do so in a loop, you would just need to call it several times, although you will want to store the values in a structure that will not override the previous.

### #8 ndc85430

• I think you'll find it's "Dr"

Reputation: 934
• Posts: 3,740
• Joined: 13-June 14

## Re: First time working with Python and OOP

Posted 24 January 2016 - 11:40 PM

Note that your Point class represents more than one point. A point is defined by only one pair of coordinates.

### #9 DK3250

• Pythonian

Reputation: 499
• Posts: 1,562
• Joined: 27-December 13

## Re: First time working with Python and OOP

Posted 25 January 2016 - 12:32 AM

I agree with nds85430, an instance of the Point class should only hold one point, i.e. one x-value and one y-value. Furthermore, you'll need a list of all Point instances; this can be achieved along with the input, like this:
```all_points = []
input_loop:  # can be a for loop, function call, coded loop, from file or other..
x =  # input
y =  # input
all_points.append(Point(x, y))  # creates a Point instance and appends it to the list
```
Later you can access the points by
```for point in all_points:
# ..some code
```

The Distance class should be accessed like
```dist = Distance(point1, point2)
```
If distance is not used with other attributes or methods, a class is more then you need, a simple function will do. But this depends of your code needs.

### #10 pigeonwiki

Reputation: 0
• Posts: 4
• Joined: 22-January 16

## Re: First time working with Python and OOP

Posted 26 January 2016 - 01:29 PM

Now I am understanding the idea of multiples instance through a list.
```class Point():
def __init__(self, x, y):
self._x = x
self._y = y

```

I passed the values to the method of the instance df. There's a difference in pass the values directly to the instance?
```class Distance():
def execFormula(self, point0, point1):
print('d = (({} - {})^2 + ({} - {})^2)^1/2'.format(point0._x, point1._x, point0._y, point1._y))
x = point0._x - point1._x
y = point1._y - point1._y

```

Now this is a for loop!!
```def main():
pointList = []

for z in range(2):
x = int(input('x: '))
y = int(input('y: '))
pointList.append(Point(x, y))

df = Distance()
df.execFormula(pointList[0], pointList[1])

if __name__ == '__main__': main()

```

### #11 DK3250

• Pythonian

Reputation: 499
• Posts: 1,562
• Joined: 27-December 13

## Re: First time working with Python and OOP

Posted 26 January 2016 - 02:11 PM

This looks really good.

In my view you can settle for a simple function to do what you do in the Distance class. But fine for practice.

Only if you need more instances of Distance (say, between many pair of points), do you really need a class - in that case you should create the instances with the def __init__(self, point0, point1) call.

### #12 pigeonwiki

Reputation: 0
• Posts: 4
• Joined: 22-January 16

## Re: First time working with Python and OOP

Posted 26 January 2016 - 07:13 PM

Wow. Thanks for all the comments and observations in the source code, Now I understand much better the objects!

This is a final version of the exercise.

```class Point():
def __init__(self, x, y):
self._x = x
self._y = y

class Distance():
def __init__(self, point0, point1, d = 0):
self.p0 = point0
self.p1 = point1
self._d = d

def execFormula(self):
print('d = (({} - {})^2 + ({} - {})^2)^1/2'.format(self.p0._x, self.p1._x, self.p0._y, self.p1._y))
x = self.p0._x - self.p1._x
y = self.p1._y - self.p1._y

print('d = (({})^2 + ({})^2)^1/2'.format(x, y))
x = x ** 2
y = y ** 2

print('d = ({} + {})^1/2'.format(x, y))
self._d = x + y

print('d = ({})^1/2'.format(self._d))
self._d = self._d ** .5

print('d = {} \n'.format(self._d))

def main():
pointList = []

for z in range(4):
x = int(input('x: '))
y = int(input('y: '))
pointList.append(Point(x, y))

df = Distance(pointList[0], pointList[1])
df.execFormula()

df1 = Distance(pointList[2], pointList[3])
df1.execFormula()

if __name__ == '__main__': main()

```

### #13 DK3250

• Pythonian

Reputation: 499
• Posts: 1,562
• Joined: 27-December 13

## Re: First time working with Python and OOP

Posted 27 January 2016 - 01:55 AM

Please observe that you have a direct failure in line 15; - I'm sure you can find it...

### #14 DK3250

• Pythonian

Reputation: 499
• Posts: 1,562
• Joined: 27-December 13

## Re: First time working with Python and OOP

Posted 27 January 2016 - 02:05 AM

Just for demonstration: Suppose you have four points and you want distance of all possible combinations:
```def main():
pointList = []

for z in range(0, 8, 2):  # dummy values avoiding input from console during test
x = z
y = z+1
pointList.append(Point(x, y))

for i, p1 in enumerate(pointList):
for p2 in pointList[i+1:]:
df = Distance(p1, p2)
df.execFormula()

if __name__ == '__main__': main()
```