A Class, in Object Oriented Programming, can have attributes (sometimes called variables or properties). Objects created from a class have all of the classes variables. But their value is set not in the class but in the objects themself.

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

Related course: Python Programming Courses & Exercises

Attributes example

In OOP you use many classes throughout your code. An empty class has no use, so start with a class that has one or more variables. A class is creates in the snippet below, which has two variables.

Code to create a class named product:

class Product:
name = ''
ingredients = []

Create an object (an instance). On the instance you can set the objects variables. You assign attribute values by using the dot (.) between the objects name and the variable, followed by the equality sign and the value.

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.

These values are unique to the object, meaning if you create another object it’s
values won’t be the same. A value can be a number (int, float), a string or even a list (you can assign a set of values to the list).

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

Visually this is what’s happening. A class is created with some variables. By using the class, two objects are created. Each object can have different properties (atributes).

class attributes

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

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

Constructor

Do you have to set each objects attribute manually, line by line?

No, there’s a trick you can use, the so called constructor.

Instead of doing it manually:

pancake.name = "Pancake Strawberry"
pancake.price = 5
pancake.taste = "Sweet"

You can intialize all the properties using the constructor:

pancake = Product("Pancake Strawberry", 5, "Sweet")

Python doesn’t understand this by default, you need to define what to do in the class, by make it.

You can use a class its constructor (a special function) to set the objects variables on creation. The sole purpose of a constructor is to intialize the object with values.

You use a class’s constructor each time you initialize a new object (the parameters are used to set the objects attributes).

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)

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

Download exercises