category: OOP | Python Tutorial

Category: OOP

Object Oriented Programming

In this series, we’ll explore Object Oriented Programming.

Everything is an object in Python.

Sometimes the terms objects and classes are mixed, but they are different concepts.

Related course: Complete Python Bootcamp: Go from zero to hero in Python 3
icon

Object

An object can contain variables and/or methods that interact with those variables.
Sometimes objects are named after real world objects.
In a RC car program, you may find:

servoMotor = Motor()
servoMotor.turnOn()

The first line creates the object. The second line calls the method turnOn(). That method may modify the objects variables.

Objects are not always named after real world objects. In the context of the program, it could even have a one letter name. Consider:

r = Robot()

You may often find other non real-world names. It’s common that applications have some objects that make sense only to coders, like HTTPFetcher or HTMLParser.

Class

An object doesn’t appear out of the blue. It’s created with help of a class. A class is a grouping of methods and variables, sort of an abstract model.

Objects are always created using classes. A class defines an objects methods and variables, but it doesn’t hold the actual variable data.

Objects can be created a runtime - when the program is running. Classes are always defined in the code, before the program starts.

Class

In Python everything is an object. An object has zero or more methods.
Thus far you have already worked with objects. Let’s take an example:

s = [1,2,3,4]
s.reverse()
s.append(2)
s.remove(1)

In the above example, we have an object named s (a list). This object has the methods reverse(), append() and remove().

Related course: Complete Python Bootcamp: Go from zero to hero in Python 3
icon

Class example

Example 1
To create new types of objects, we must define a class.

class ShoppingList:
products = []

def __init__(self):
print('Shopping list created')

def add(self, name):
self.products.append(name)

def show(self):
print(self.products)

groceries = ShoppingList()
groceries.add('Peanutbutter')
groceries.add('Milk')
groceries.show()

We create an object named groceries, of the type ShoppingList.

class

We then use the methods add() and show().
We also defined a class named ShoppingList which has these methods defined.

Note: there is a method named init(), which is always called upon creation of an object. This is named the constructor.

Example 2
We create an object of the type car, named superCar. The superCar object has one method drive().
In addition to the the init method (also called constructor) that is called when you create new objects.

class Car:
def __init__(self):
print('Car created')

def drive(self):
print('Engine started')

superCar = Car()
superCar.drive()

Class attributes

A class can have attributes (sometimes called variables).

Objects created from a class have all of the parent classes variables.

This allows us to do Object Orientated Programming: we speak about (albeit) virtual objects. Those objects can have unique properties.

Related course: Complete Python Bootcamp: Go from zero to hero in Python 3
icon

Attributes example

Start with a class that has variables.
Create a class product:

class Product:
name = ''
ingredients = []

Create an object. Then you can set the objects variables:

pancake = Product()
pancake.name = 'Pancake'
pancake.ingredients = [ 'Milk','Sugar' ]

You can create multiple objects from a class. Each object has unique values for the variables.

cookies = Product()
cookies.name = 'Cookies'
cookies.ingredients = [ 'Sugar' ]

Those objects can be used in your program. You can use an objects variables:

print(pancake.name)
print(cookies.name)

You can use a class its constructor to set the objects variables on creation:

class Product:
name = ''
ingredients = []

def __init__(self, name, ingredients):
self.name = name
self.ingredients = ingredients

pancake = Product('Pancake', ['Milk','Sugar'])
cookies = Product('Cookies', ['Sugar'])
print(pancake.name)
print(cookies.name)

Class Methods

Objects can call methods, those methods are defined in classes.

Methods can modify all variables of an object. This is done with the self keyword.

Because methods can be called from an object (instance), they are sometimes called instance methods.

Related course: Complete Python Bootcamp: Go from zero to hero in Python 3
icon

python class methods

If you have a class Phone, you can create a new phone object (Nexus).

In this example the class has a method addContact. We call this method in the object, which changes the phones contact list.

nexus = Phone()
nexus.addContact('Faith')

The class itself has the methods and variables:

class Phone:
contacts = []

def call(self):
print('Calling')

def addContact(self, name):
self.contacts.append(name)

Every object you create has unique variables. If you create 3 objects, all of them have their own unique variables.

In the example above, we create an object Nexus.

class_methods

On this object we can call the methods call() and addContact(). Those methods are defined in the class, but change the objects variables.

Related course:

In the next article we’ll discuss the self keyword.

Constructor

A constructor is the first method that is called on object creation.

The constructor is always called when creating a new object.
It can be used to initialize class variables and startup routines.

Related course: Complete Python Bootcamp: Go from zero to hero in Python 3
icon

python constructor example

In the example below we create a class C with a constructor and the method see. \

We create one object C. On execution it will output both lines because we call the method and when creating the object it calls the constructor.

In Python a constructor is written as init(self)

class C:
def __init__(self):
print('Constructor called.')

def see(self):
print('C')

obj = C()
obj.see()

This will output:

Constructor called.
C

Watch how the output of the constructor is shown first.


1234