Class and object variables

Class and object variables

In Python, class variables and instance variables are two types of variables that can be defined in a class.

Class variables are variables that are shared by all instances of a class. They are defined inside the class definition, but outside of any methods. Here’s an example:

pythonCopy codeclass MyClass:
    class_var = 0

In this example, class_var is a class variable that is set to 0. This variable is shared by all instances of the MyClass class.

To access a class variable, we can use either the class name or an instance of the class:

pythonCopy codeprint(MyClass.class_var)  # prints 0

obj = MyClass()
print(obj.class_var)  # prints 0

Instance variables, on the other hand, are variables that are unique to each instance of a class. They are defined inside the __init__() method of the class. Here’s an example:

pythonCopy codeclass MyClass:
    def __init__(self, instance_var):
        self.instance_var = instance_var

In this example, instance_var is an instance variable that is initialized with the instance_var argument passed to the __init__() method.

To access an instance variable, we need an instance of the class:

pythonCopy codeobj = MyClass(42)
print(obj.instance_var)  # prints 42

Each instance of the MyClass class has its own instance_var variable with its own value.

Overall, class variables and instance variables allow us to define variables in a class that can be shared or unique to each instance of the class.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Share this post
[social_warfare]
Object methods and the init method
Inheritance

Get industry recognized certification – Contact us

keyboard_arrow_up