Python can create objects. An object is a collection of methods and variables.
Objects are always created from classes.

A program can have multiple classes and objects. This concept is known as object orientated programming.

classes

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

Example

If an object is created, the method init is called. The self keyword is required in methods and variables to tell Python they belong to the class.

#!/usr/bin/python
class Website:
def __init__(self,title):
self.title = title

def showTitle(self):
print(self.title)

obj = Website('pythonbasics.org')
obj.showTitle()

In this example we have one object (obj), created from the class Website. The class has two methods: init() and showTitle().

Exercise

Try the exercises below

  1. Using the code above, create another object

  2. Add a method to the class: location()

After completing these continue with the next exercise.

Download answers