Interview Questions, Answers and Tutorials

Class variables and static methods

Class variables and static methods

Welcome to our technical course on class variables and static methods in Python! In this course, we will delve into the concepts of class variables and static methods, which are fundamental aspects of object-oriented programming (OOP) in Python. We’ll break down these concepts in a simple and easy-to-understand manner, perfect for beginners and enthusiasts alike.

1. Understanding Class Variables:

In Python, a class variable is a variable that is shared among all instances (objects) of a class. It is declared within the class but outside any method. Let’s take a look at an example:

class Car:
    wheels = 4  # Class variable
    def __init__(self, brand):
        self.brand = brand

car1 = Car("Toyota")
car2 = Car("Tesla")

print(car1.wheels)  # Output: 4
print(car2.wheels)  # Output: 4

Here, wheels is a class variable. Both car1 and car2 instances share this variable, and any changes made to it will reflect across all instances.

2. Implementing Static Methods:

Static methods in Python are methods that are bound to a class rather than its instances. They do not operate on instance data and do not require access to instance attributes. Let’s see an example:

class MathOperations:
    def add(x, y):
        return x + y
    def subtract(x, y):
        return x - y

print(MathOperations.add(5, 3))       # Output: 8
print(MathOperations.subtract(10, 4))  # Output: 6

In this example, add and subtract are static methods. They can be called directly on the class without creating an instance.

3. Practice Questions:

  1. Class Variables Question:
class Dog:
    legs = 4
dog1 = Dog()
dog2 = Dog()

dog1.legs = 3

print(dog1.legs)  # Output?
print(dog2.legs)  # Output?


  1. Static Methods Question:
class Converter:
    def feet_to_meters(feet):
        return feet * 0.3048
print(Converter.feet_to_meters(10))  # Output?

Output: 3.048

Congratulations! You have completed our course on class variables and static methods in Python. You now have a solid understanding of how these concepts work and how to implement them in your own Python programs. Keep practicing and experimenting to reinforce your learning. Happy coding!