Overview
Welcome back to our Python programming tutorial. In this article, we will discuss the important concepts of instance variables and class attributes:
- Instance variables are variables that are unique to each instance of a class.
- Class attributes are variables that are shared by all instances of a class.
We will use the Coffee class to illustrate the difference between instance variables and class attributes. Unlike our previous article that discussed class, object and constructor, this time, our Coffee class will be associated with the price of the coffee instead of calories.
class Coffee:
name = "Coffee"
price = 1.00
def __init__(self, name, price):
self.n = name
self.p = price
The name
and price
variables are class attributes. They are shared by all instances of the Coffee class.
The self.n
and self.p
variables are instance variables. They are unique to each instance of the Coffee class.
For example, the following code creates two instances of the Coffee class:
drink1 = Coffee("Latte", 2.00)
drink2 = Coffee("Espresso", 1.50)
The drink1
instance has a name
of "Latte
" and a price
of 2.00
. The drink2
instance has a name
of "Espresso
" and a price
of 1.50
.
The name
and price
class attributes are shared by both instances. However, the self.n
and self.p
instance variables are unique to each instance.

Class attributes and instance variables are important concepts in Python programming. By understanding the difference between these two types of variables, you can write more efficient and effective code. Now, let’s explore them in detail.