Python and Objects

Using classes and objects in Python should be your standard approach to keep your code clean and optimizable. Here is an example of a class Location. The class contains a number of properties, such as name and x and y coordinates. In practice, classes often have several tens of properties. Classes can contain methods. In this case the method is distance(), which calculates the distance between this object and another object of class Location.

l1 and l2 are objects that are instantiated from the class Location. You can verify that by using the built-in type().

Meaningful names

In many projects, class names are garbled. This is because initially we just needed a class name, and later on it turned out not to be quite appropriate. But: too late, because we are using the class already.

For the sake of maintenance, change your class names to something someone else will understand. And: be consistent in your notation. Whether you use lower Camel Case or Upper Camel Case or any other notation, be consistent! 

Using Classes and Objects

import geopy.distance
import math

class Location:
  def __init__(self, name, x, y):
    self.name = name
    self.x = x
    self.y = y
    self.coords = (x, y)

  def distance(self, otherLocation):
    dist = geopy.distance.distance(self.coords, otherLocation.coords).km  
    return dist

l1 = Location("Bob's diner", 42.344250, -75.170448)
l2 = Location("My own location", 51.903969, 4.484250)
print('The distance between {} and {} is {:.2f} km'.format(l2.name, l1.name, l2.distance(l1)))

Check the types

print(type(l1), type(l2))

Previous chapter | Next chapter