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: Python Object Oriented Programming

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'
pancake.ingredients = [ 'Milk','Sugar' ]

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

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

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


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

class Product:
name = ''
ingredients = []

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

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

Previous Post Next Post

Cookie policy | Privacy policy | ©