Python

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 Beyond the Basics – 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.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)

Previous Post Next Post

Cookie policy | Privacy policy | ©

OOP