Skip to content

What is an instance variable in Python | Example code

  • by

Python Instance variables are variables that have their unique value to a particular instance. The instance variables are owned by an instance (Object) of a class. They are declared inside a class method.

Example instance variable in Python

Simple example code student class example below, name and age are instance variables:

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


s1 = Student('John', 18)
s2 = Student('Tim', 70)

print(s1.name)
print(s2.name)

Output:

instance variable in Python

Different ways to access Instance Variable in Python

Using Self and object reference

class Student:

    def __init__(self, name, age):
        # instance variable
        self.name = name
        self.age = age

    def display(self):
        # using self to access variable inside class
        print("Name:", self.name, "Age:", self.age)


s1 = Student('John', 18)
s2 = Student('Tim', 70)

s1.display()
s2.display()

Output:

Name: John Age: 18
Name: Tim Age: 70

Using getattr()

class Student:

    def __init__(self, name, age):
        # instance variable
        self.name = name
        self.age = age

    def display(self):
        # using self to access variable inside class
        print("Name:", self.name, "Age:", self.age)


s1 = Student('John', 18)
s2 = Student('Tim', 70)

print(getattr(s1, 'name'))
print(getattr(s2, 'name'))

Output:

John
Tim

Do comment if you have any doubts or suggestions on this Python variable topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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