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: Python Programming Courses & Exercises

What are classes and objects in Python?

Python is an object orientated language, objects are essential to it. So what is an object?

An object is a collection of variables and methods (the objects methods interact with the objects data).

Everything in Python is an object.

If you have a string object, it can hold a variable (the string value).

>>> s = "hello"

Then you can use methods to interact with the objects variable:

>>> s.
s.capitalize() s.encode() s.format() s.isalpha() s.isidentifier() s.isspace() s.ljust() s.partition() s.rjust() s.split() s.swapcase() s.zfill()
.casefold() s.endswith() s.format_map() s.isascii() s.islower() s.istitle() s.lower() s.replace() s.rpartition() s.splitlines() s.title()
s.center() s.expandtabs() s.index() s.isdecimal() s.isnumeric() s.isupper() s.lstrip() s.rfind() s.rsplit() s.startswith() s.translate()
s.count() s.find() s.isalnum() s.isdigit() s.isprintable() s.join() s.maketrans() s.rindex() s.rstrip() s.strip() s.upper()

Each object is created from a class. A class is like a blue print for an object.

To see which class an object is created from, you can call the type() method.

>>> type(s)
<class 'str'>

An object oriented program often has many different classes and objects.

If you are a Python beginner, then I highly recommend this book.

Python class

A class is defined with the keyword class.

Classes can have methods, that start with the keyword def.

The most simple class you can create is an empty class:

class Drink:
pass

The class can then be used to create one or more objects.
Objects are created like this:

tea = Drink()
juice = Drink()
coffee = Drink()

The class can have one or more variables:

class Drink:
price = 0

Objects can then set the variable (after creation)

tea = Drink()
juice = Drink()
coffee = Drink()

tea.price = 1
juice.price 1.25
coffee.price = 1.50

The values are unique to each object.

python class

But the class defines which variables exist for the objects.

If you don’t define the variable in the class, it throws an error:

>>> class Drink:
... price = 0
...
>>> tea = Drink()
>>> tea.color = green
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'green' is not defined
>>>

To solve that, add the variables you want to the class.

>>> class Drink:
... price = 0
... color = ''

You can have more than one class in your program.

The objects should be created from a class that’s an objects abstraction.
And so, if you want an object ‘car’, you don’t want to create it from a class named ‘Drink’ because the variables and methods would make no sense.

Constructors in Python

The class before had only two variables, but a class can have many many variables.

Say a class has ten variables, then you’d have to set an objects variables like this:

obj1.var1 = ...
obj1.var2 = ...
obj1.var3 = ...
obj1.var4 = ...
...
obj1.var10 = ...

This quickly becomes a lot of typing work.

Mind you that you then need to do that for each object.

To make life simpler, you can use a constructor.

A constructor is a method that sets the objects variables.

By default, a constructor is called during object creation.

obj1 = MyClass(var1,var2,var3,var4...)

To do this, you need to modify the class.

You add the constructor which is the __init__ method.

>>> class Drink():
... def __init__(self, price, color):
... self.price = price
... self.color = color
...

In this method you set the objects variables. The word self refers to the created object.

Then you can create objects like this:

>>> soda = Drink(2,'blue')
>>> milkshake = Drink(3,'white')

Each object has the variables set upon creation using the constructor.

Each class can have exactly one constructor, like in the image below where the constructors are highlighted.

python constructor

If you are a Python beginner, then I highly recommend this book.

Object methods

Objects can contain methods, these methods interact with the objects data.

The class below has one method, that outputs the objects variable value.

The word self means the object, similar to how we use my in English.

Then my.name is unique to every person. In the same way self.name is unique to every object.

>>> class Person:
... name = ''
... def who(self):
... print("I am " + self.name)
...

After definition of the class you can create one or more objects.

Every object can iteract with the associated class methods.

>>> u123 = Person()
>>> u123.name = "Alice"
>>>
>>> u123.who()
I am Alice
>>>

A class can have more than one method.

You can see which methods and variables are available, by typing the objects name, a dot and then the tab key.

>>> u123.
u123.name u123.who(

You can extend the class with a constructor (as described above) and several other methods:

>>> class Person:
... # constructor
... def __init__(self, name, job):
... self.name = name
... self.job = job
... def setName(self, name):
... self.name = name
... def setJob(self, job):
... self.job = job
... def who(self):
... print("I am " + self.name + " and I am a " + self.job)
...

Then create some objects:

>>> user1 = Person("Alice","Hairdresser")
>>> user2 = Person("Cassy", "Carpenter")

And each method can interact with the objects variables:

>>> user1.who()
I am Alice and I am a Hairdresser
>>>
>>> user2.who()
I am Cassy and I am a Carpenter
>>>

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()

Deleting objects

If you wan to do delete object after creation, that’s possible.

An object can be deleted with the del statement.

So first create some objects

>>> alice = User()
>>> bob = User()
>>> cassy = User()

Then delete one or more:

>>> del bob

If you try to access a deleted object, you’ll see this error:

>>> bob
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bob' is not defined
>>>

An existing object will show something like this:

>>> alice
<__main__.User object at 0x7f6119c0bc90>

Deleting object is possible, but in most cases not necessary.

You can also delete class attributes at run tme, but this is not recommended.

>>> class Drink:
... price = 0
... color = ''
...

To delete an attribute use del again.

>>> # delete attribute at runtime
>>> del Drink.color
>>> Drink.color
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'Drink' has no attribute 'color'
>>>

If you are a Python beginner, then I highly recommend this book.

Download exercises