w3resource

What are instance variables in Python classes?

Understanding instance variables in Python classes

In Python classes, instance variables are variables that are unique to each instance (object) of the class. They are defined within the class and used to store data specific to individual objects. It is possible for objects of the same class to have their own independent data through instance variables.

Instance variables are typically defined within the '__init()__' method, also known as the constructor. This method is automatically called when an object is created. The '__init()__' method initializes instance variables with initial values.

Example: A Python class with instance variables

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
# Creating instances of the class
person1 = Person("Taimi Dikla", 30)
person2 = Person("Naoise Eunike", 25)

In this example, we have a class "Person" with two instance variables: 'name' and 'age'. These variables are defined within the '__init()__' method, and each instance of the class ('person1' and 'person2') has its own separate copies of these instance variables.

For 'person1', the 'name' instance variable will be set to "Taimi Dikla" and the 'age' instance variable will be set to 30. Similarly, for 'person2', the 'name' instance variable will be set to "Naoise Eunike" and the 'age' instance variable will be set to 25.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-interview/what-are-instance-variables-in-python-classes.php