Lesson 1 of 0
In Progress

Lesson #13: Classes & Objects

Classes are used to create user-defined data structures. Classes define functions called methods, which identify the behaviors and actions that an object created from the class can perform with its data.

Create Your Own Function

To create a class, use the keyword class.

Example

Create a class named Coordinates, with a property named num:

class Coordinates:
  num = 5

The Coordinates class isn’t very interesting right now, so let’s spruce it up a bit by defining some properties that all Coordinates objects should have. To keep things simple, we’ll just use x and y.

The properties that all Coordinates objects must have are defined in a method called __init__().

The __init()__ Function

The examples above are classes and objects in their simplest form and are not really useful in real-life applications. All classes have a function called __init__(), which is always executed when the class is being initiated.

Use the __init__() function to assign values to object properties or other operations that are necessary to do when the object is being created:

Example

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

In the body of __init__(), there are two statements using the self variable:

  1. self.x = x creates an attribute called x and assigns to it the value of the x parameter.
  2. self.y = y creates an attribute called y and assigns to it the value of the y parameter.

Create Object

Now we can use the class named Coordinates to create objects.

Example

Create an object named map, and print the value of x and y:

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

map = Coordinates(41.40338, 2.17403)

print(map.x)
print(map.y)

Create Object Methods

Object methods are functions that are defined inside a class and can only be called from an instance of that class. Let’s create a method in the Coordinates class.

Example

Create a function name message that prints a text, and execute it on the map object.

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

  def message(self):
    print(“The latitude is: “ + self.x)
    print(“The longitude is: “ + self.y)

map = Coordinates(41.40338, 2.17403)
map.message()