Python Class Variables with Examples

Posted in

Python Class Variables with Examples
vinaykhatri

Vinay Khatri
Last updated on December 22, 2024

    In Python class, we can define two types of variables

    1. Instance Variables

    The instance variables of the class are bound to the class object, and they are defined in the method using the self. prefix.

    Example

    class A:
    
        def __init__(self, x, y):
            #self.x and self.y are instance variables
            self.x = x
            self.y = y

    2. Class Variables

    The variables that are defined inside the outside the class instance method or inside the class methods are the class variables.

    Example

    class A:
    
        #x and y are the class variables
        x1 = 23
        y2 = 45
    
        def __init__(self, x, y):
    
            #self.x and self.y are instance variables
            self.x = x
            self.y = y

    This Python tutorial discusses what are Class variables in Python and how to define them. By reading this article you will build a solid understanding on

    • What is a class variable in Python
    • How to create class variables
    • How to access class variables in Python
    • How to modify class variables
    • What is the difference between class and instance variables
    • Working of class variables with inheritance
    • Wrong practice of class variables

    What are class variables in Python?

    Class variables are those variables that are defined inside the class and class methods, but outside the instance method without using the self keyword. The value of the class variables does not change object to object, it remains the same for all the objects of the class. In Python, Class variables are generally declared inside the class body and outside all the methods. For example, we have an employee class that holds the record of different employees' objects, the details of the employees may be different but some details are common such as company name. In that case, the name of the employee comes under instance variables and the company name comes under class variable.

    How to create class variables in Python?

    Now let’s write the python code for the example that we have discussed in the above example. Conventionally all the class variables are defined just after the class name heading and before the constructor, __init__() method.

    Example

    class Employee:
    
        #class variable
        company_name = "TechGeekBuzz"
    
        #initialize the instance variables using constructor
        def __init__(self, id, name):
            #instance variables
            self.id = id
            self.name = name        
    
        #instance method
        def detail(self):
            print("Employee ID:", self.id)
            print("Employee Name:", self.name)

    In this example, company_name is the class variable for the class Employee Note: The class variable is like other variables, and it follows the same naming rules.

    Accessing the class variables

    The class variable can be accessed inside and outside the class using the class name. Python allows us to use different syntax to access a class variable such as

    1. We can access the class variables inside the instance methods using the self parameter.
    2. We can also access the class variables inside the instance method using the class name.
    3. And for accessing the class variables outside the class we can use the class name.

    Example

    Access the class variable inside the instance method using the self parameter

    class Employee:
        #class variable
        company_name = "TechGeekBuzz"
    
        #initialize the instance variables using constructor
        def __init__(self, id, name):
    
            #instance variables
            self.id = id
            self.name = name        
    
        #instance method
        def detail(self):
            #access the class variable using self 
            print("Company Name: ", self.company_name)
    
            #access instance variables using self
            print("Employee ID:", self.id)
            print("Employee Name:", self.name)
    
    e1 = Employee('TGB01', 'Rohit')
    
    e1.detail()

    Output

    Company Name:  TechGeekBuzz
    Employee ID: TGB01
    Employee Name: Rohit

    Example

    Access the class variable inside the instance method using the class name

    class Employee:
    
        #class variable
        company_name = "TechGeekBuzz"
    
        #initialize the instance variables using constructor
        def __init__(self, id, name):
            #instance variables
            self.id = id
            self.name = name        
    
        #instance method
        def detail(self):
    
            #access the class variable using class name 
            print("Company Name: ", Employee.company_name)
    
            #access instance variables using self
            print("Employee ID:", self.id)
            print("Employee Name:", self.name)
    
    e1 = Employee('TGB01', 'Rohit')
    
    e1.detail()

    Output

    Company Name:  TechGeekBuzz
    Employee ID: TGB01
    Employee Name: Rohit

    Example

    Access the class variable outside the class using the class name or object name We can either use the class name or the object name to access the class variable outside the class.

    class Employee:
    
        #class variable
        company_name = "TechGeekBuzz"
    
        #initialize the instance variables using constructor
        def __init__(self, id, name):
            #instance variables
            self.id = id
            self.name = name        
    
        #instance method
        def detail(self):
            #access the class variable using class name 
            print("Company Name: ", Employee.company_name)
    
            #access instance variables using self
            print("Employee ID:", self.id)
            print("Employee Name:", self.name)
    
    e1 = Employee('TGB01', 'Rohit')
    
    print("Class Variable company_name(using object):", e1.company_name)
    print("Class Variable company_name(using Class):", Employee.company_name)

    Output

    Class Variable company_name(using object): TechGeekBuzz
    Class Variable company_name(using Class): TechGeekBuzz

    Note: When it comes to accessing the class variables it's always suggested to use the class name rather than self and the object name. Because when we try to modify the class variable using self or object name, it creates a new instance variable as a copy of the class variable, and changes only occur for that object.

    How to modify the class variables?

    After defining a class variable inside a class we can change its value from outside and inside the class. To modify the class variable value outside the class we should use the class name followed by the dot operator, variable name, and assign a new value to it.

    Example Modify the class variable outside the class.

    class Employee:
        #class variable
        company_name = "TGB"
    
        #initialize the instance variables using constructor
        def __init__(self, id, name):
            #instance variables
            self.id = id
            self.name = name        
    
        #instance method
        def detail(self):
            #access the class variable using class name 
            print("Company Name: ", Employee.company_name)
    
            #access instance variables using self
            print("Employee ID:", self.id)
            print("Employee Name:", self.name)
    
    e1 = Employee('TGB01', 'Rohit')
    e2 = Employee('TGB02', 'Joshi')
    
    print("Details Before updating the Class variable:\n\n")
    
    e1.detail()
    
    print()
    
    e2.detail()
    
    #modify the class variable company_name outside the class
    Employee.company_name = "TechGeekBuzz"
    
    print("\n\n\n\nDetails After updating the Class variable:\n\n")
    
    e1.detail()
    
    print()
    
    e2.detail()

    Output

    Details Before updating the Class variable:
    
    Company Name:  TGB
    Employee ID: TGB01
    Employee Name: Rohit
    
    Company Name:  TGB
    Employee ID: TGB02
    Employee Name: Joshi
    
    Details After updating the Class variable:
    
    Company Name:  TechGeekBuzz
    Employee ID: TGB01
    Employee Name: Rohit
    
    Company Name:  TechGeekBuzz
    Employee ID: TGB02
    Employee Name: Joshi

    In this example, you can see that we have only changed the Employee.compnay_name and the changes reflect on both the objects. This is because the class variable is shared by all the class object and its value remain the same for all object of the class. To modify the class variable inside the class we can take the help of static or classmethod.

    Example

    class Employee:
    
        #class variable
        company_name = "TGB"
    
        #initialize the instance variables using constructor
        def __init__(self, id, name):
            #instance variables
            self.id = id
            self.name = name        
    
        #instance method
        def detail(self):
            #access the class variable using class name 
            print("Company Name: ", Employee.company_name)
    
            #access instance variables using self
            print("Employee ID:", self.id)
            print("Employee Name:", self.name)
    
        #static function 
        def change_company_name():
            #modify the class variable
            Employee.company_name = "TechGeekBuzz"
    
    e1 = Employee('TGB01', 'Rohit')
    e2 = Employee('TGB02', 'Joshi')
    
    print("Details Before updating the Class variable:\n\n")
    e1.detail()
    print()
    e2.detail()
    
    #modify the class variable with class Employee
    Employee.change_company_name()
    
    print("\n\n\n\nDetails After updating the Class variable:\n\n")
    e1.detail()
    print()
    e2.detail()

    Output

    Details Before updating the Class variable:
    
    Company Name:  TGB
    Employee ID: TGB01
    Employee Name: Rohit
    
    Company Name:  TGB
    Employee ID: TGB02
    Employee Name: Joshi
    
    Details After updating the Class variable:
    
    Company Name:  TechGeekBuzz
    Employee ID: TGB01
    Employee Name: Rohit
    
    Company Name:  TechGeekBuzz
    Employee ID: TGB02
    Employee Name: Joshi

    In this example, you can see that the function change_company_name() defined inside the class can be called using Employee class and it can change the class variable company_name for all the objects. In the above example, we have used the static method to change the class variables, but when we deal with class variables and their modification it's always suggested to use the classmethod rather than static or instance methods.

    class Employee:
    
        #class variable
        company_name = "TGB"
    
        #initialize the instance variables using constructor
        def __init__(self, id, name):
            #instance variables
            self.id = id
            self.name = name        
    
        #instance method
        def detail(self):
            #access the class variable using class name 
            print("Company Name: ", Employee.company_name)
    
            #access instance variables using self
            print("Employee ID:", self.id)
            print("Employee Name:", self.name)
    
        #static function
        @classmethod
        def change_company_name(cls):
            #modify the class variable
            #the cls is the class of object that is calling this method
            cls.company_name = "TechGeekBuzz"
    
    e1 = Employee('TGB01', 'Rohit')
    e2 = Employee('TGB02', 'Kiran')
    
    print("Details Before updating the Class variable:\n\n")
    e1.detail()
    print()
    e2.detail()
    
    #modify the class variable with one class object e1
    e1.change_company_name()
    
    print("\n\n\n\nDetails After updating the Class variable:\n\n")
    e1.detail()
    print()
    e2.detail()

    Output

    Details Before updating the Class variable:
    
    Company Name:  TGB
    Employee ID: TGB01
    Employee Name: Rohit
    
    Company Name:  TGB
    Employee ID: TGB02
    Employee Name: Kiran
    
    Details After updating the Class variable:
    
    Company Name:  TechGeekBuzz
    Employee ID: TGB01
    Employee Name: Rohit
    
    Company Name:  TechGeekBuzz
    Employee ID: TGB02
    Employee Name: Kiran

    In this example, you can see that we used the classmehtod to update the value of class variable company_name . When the e1 object called the change_company_name method, it passes the Employee as the cls parameter to the change_company_method() method.

    What is the difference between class variables and Instance variables

    In Python object-oriented programming two types of variables are often used:

    1. Instance variables: Instance variables are those variables that are defined inside the __init__() and instance method and that start with self. name. The value of the instance variable can vary from object to object and the variables are bound to the objects of the class.
    2. Class variables: Class variables are defined in the global scope of the class body, which means outside every method of the class. The class variable is shared between every object of the class and its value remains the same for every object of the class.

    Head-to-head comparison between Instance and Class variables

    Instance variables Class variables
    The instance variables are created and accessed using the self parameter. Class variables are created like normal variables but inside the class body and outside every method, and to access it we can use the class name.
    With each object creation of the class, the copy of instance variables is also created. This means every object has its own copy of instance variables. Class variables are shared between the objects and their value remains the same for every object.
    The Instance variable gets created when the object is created. The class variable is created when the code is executed.
    Changes made on instance variables of one object do not reflect on others. Changes made on the class variables reflect on every object.

    Working of class variables with Inheritance

    When a child class inherits the parent class, the child class becomes able to access the properties and methods of the parent class. Class variables are no exceptions, the child class also accesses the class variables of the parent class when it inherits the parent class, and we can access the parent class variables using the child class name.

    Example

    class Parent():
        total_wealth = 100000
    
    class Child(Parent):
        def __init__(self,name):
            self.name = name
    
    #access the class variable of the parent class
    print(Child.total_wealth)

    Output

    100000

    If the parent and child class have the same class variable name in that case the child variable will give priority to its class variable.

    Example

    class Parent():
        #class variable of parent 
        total_wealth = 100000
    
    class Child(Parent):
        #class variable of child
        total_wealth = 99999
        def __init__(self,name):
            self.name = name
    
    #access the class variable 
    print(Child.total_wealth)

    Output

    99999

    Because of the priority Child class will first access its class variable rather than accessing its parent class variables. So it’s always recommended to used different names for the class variables.

    Wrong practice of class variables

    Class variables are an important part of Python class and methods because changing class variables in one object show the changes in all the other objects as well that’s why we should use it properly. They should only be used when the variable value is constant for every object. In our above example of Employee class, all the employees come under the same company name that’s why putting the company_name variable as a class variable brings more meaning to the code. Although we can also define the company_name as an instance variable such as

    class Employee:
        #initialize the instance variables using constructor
        def __init__(self, id, name):
            #instance variables
            self.id = id
            self.name = name
            self.company_name = "TechGeekBuzz"

    In this example, the company_name is the instance variable. And every time an object of Employee is created, it will create a new copy of company_name for that object . As the company name remains the same for all the employees of the Employee class, the instance variable is company_name only occupying extra space in the memory, so it's better to use it as a class variable instead of an instance variable.

    class Employee:
        #class variable
        company_name = "TechGeekBuzz"
    
        #initialize the instance variables using constructor
        def __init__(self, id, name):
            #instance variables
            self.id = id
            self.name = name

    Conclusion

    In this article, we discussed what are class variables in Python and how to declare them. Python class variables are those variables that are declared inside the class body, outside the method, and before the __init__() method. The class variables are shared by all the objects of the class and the value of the class can be accessed and modified using the Class name.

    People are also reading:

    Leave a Comment on this Post

    0 Comments