Instance Variables and Class Variables in Python. Topic – 47

Instance Variables and Class Variables

Instance Variables:

It is basically a class variable without a static modifier and is usually shared by all class instances. Across different objects, these variables can have different values. They are tied to a particular object instance of the class, therefore, the contents of an instance variable are totally independent of one object instance to others.

Syntax:

Python
class Taxes  
{  
   int count;  
   /*...*/  
}

Class Variables:

 It is basically a static variable that can be declared anywhere at class level with static. Across different objects, these variables can have only one value. These variables are not tied to any particular object of the class, therefore, can share across all objects of the class.  

Syntax:

Python
class Taxes  
{  
   static int count;  
   /*...*/  
}
Instance VariableClass Variable
It is a variable whose value is instance-specific and now shared among instances.  It is a variable that defines a specific attribute or property for a class.  
These variables cannot be shared between classes. Instead, they only belong to one specific class.  These variables can be shared between class and its subclasses. 
It usually reserves memory for data that the class needs.  It usually maintains a single shared value for all instances of class even if no instance object of the class exists.  
It is generally created when an instance of the class is created.  It is generally created when the program begins to execute.  
It normally retains values as long as the object exists.  It normally retains values until the program terminates.
It has many copies so every object has its own personal copy of the instance variable. It has only one copy of the class variable so it is shared among different objects of the class.  
It can be accessed directly by calling variable names inside the class.  It can be accessed by calling with the class name.  
These variables are declared without using the static keyword.  These variables are declared using the keyword static.  
Changes that are made to these variables through one object will not reflect in another object.  Changes that are made to these variables through one object will reflect in another object. 

Yes, I understand that it has become difficult to understand. I try my best to make concepts easy by explaining them with stories, and I will do the same for this concept as well. So, let’s start from the beginning again.

Imagine you’re running a magical pet shop where you sell extraordinary creatures. Each creature comes with its own set of unique traits and abilities. Now, let’s see how instance variables and class variables play a role in managing your magical pet shop.

Instance Variables:

Every creature you sell has its own distinct characteristics. For example, you have a mischievous dragon named Ember and a wise owl named Hootie. Each of these creatures has its own name, age, and special abilities.

Python
class Creature:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Creating instances of creatures
ember = Creature("Ember", 50)  # A mischievous dragon
hootie = Creature("Hootie", 100)  # A wise owl

Here, name and age are instance variables because they are unique to each creature. ember.name, ember.age, hootie.name, and hootie.age store the specific information for each creature.

Class Variables:

Now, let’s say you want to keep track of the total number of creatures in your shop, regardless of their individual characteristics. You can use a class variable to achieve this.

Python
class Creature:
    total_creatures = 0  # Class variable to keep track of total creatures

    def __init__(self, name, age):
        self.name = name
        self.age = age
        Creature.total_creatures += 1  # Increment total creatures when a new instance is created

# Creating instances of creatures
ember = Creature("Ember", 50)  # A mischievous dragon
hootie = Creature("Hootie", 100)  # A wise owl

print(Creature.total_creatures)  # Output: 2

In this example, total_creatures is a class variable. It’s shared among all instances of the Creature class and keeps track of the total number of creatures in your shop. Every time a new creature instance is created, the total_creatures count increases.

Let’s make it more easy.

Instance Variables:

Imagine you’re managing a library where each book has its own unique title and author. You also want to keep track of the total number of books available in the library.

Python
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

# Creating instances of books
book1 = Book("Harry Potter", "J.K. Rowling")
book2 = Book("Lord of the Rings", "J.R.R. Tolkien")

Here, title and author are instance variables because they are unique to each book. book1.title, book1.author, book2.title, and book2.author store the specific information for each book.

Class Variable:

Python
class Book:
    total_books = 0  # Class variable to keep track of total books

    def __init__(self, title, author):
        self.title = title
        self.author = author
        Book.total_books += 1  # Increment total books when a new instance is created

# Creating instances of books
book1 = Book("Harry Potter", "J.K. Rowling")
book2 = Book("Lord of the Rings", "J.R.R. Tolkien")

print(Book.total_books)  # Output: 2

In this example, total_books is a class variable. It’s shared among all instances of the Book class and keeps track of the total number of books in the library. Every time a new book instance is created, the total_books count increases.

Static Method in Python

Static Method in Python

A static method in Python does not receive an implicit first argument. A static method is also a method that is bound…

I hope you understand “Instance Variables and Class Variables in Python. Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog