PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Python Object-Oriented Programming (OOP) » Python Instance Variables Explained With Examples

Python Instance Variables Explained With Examples

Updated on: December 4, 2026 | 11 Comments

There are several kinds of variables in Python:

  • Instance variables: Variables that belong to an object. They are also called fields or attributes of an object.
  • Local variables: Variables defined inside a method or a block of code.
  • Parameters: Variables in function or method declarations.
  • Class variables: Variables shared by all objects of a class.

In object-oriented programming, when we design a class, we use instance variables and class variables.

  • Instance variables: If the value of a variable varies from object to object, the variable is called an instance variable.
  • Class variables: A class variable is declared inside the class, but outside of any instance method or the __init__() method. Its value is shared by all objects.

After reading this article, you’ll learn:

  • How to create and access instance variables
  • How to modify the values of instance variables
  • How to dynamically add or delete instance variables
  • How to check, read, and set attributes by name with hasattr(), getattr(), and setattr()
  • How an instance variable can shadow a class variable

Table of contents

  • What is an Instance Variable in Python?
  • Create Instance Variables
  • Modify Values of Instance Variables
  • Ways to Access Instance Variable
  • Check and Set Instance Variables: hasattr() and setattr()
  • Instance Variables Naming Conventions
  • Dynamically Add Instance Variable to a Object
  • Dynamically Delete Instance Variable
  • Access Instance Variable From Another Class
  • List all Instance Variables of a Object
  • Instance Variable vs Class Variable With the Same Name
  • Summary

What is an Instance Variable in Python?

If the value of a variable varies from object to object, the variable is called an instance variable. Every object gets its own separate copy of each instance variable.

Instance variables are not shared between objects. Because every object has its own copy, changing an instance variable in one object doesn’t affect any other object of the class.

Instance variables are usually used inside instance methods. An instance method performs actions on the data stored in the object’s instance variables, so we need an object to call it.

We can access an instance variable using the object and the dot (.) operator, for example stud.name.

Inside a class, we work with instance variables and methods using the self parameter. self is the first parameter of every instance method, and it refers to the current object.

Declare Instance variable in Python
Declare Instance variable

Create Instance Variables

Instance variables are created inside a method using self, in the form self.variable_name = value. Usually we define and initialize them in the constructor (__init__()), so every object starts with the same set of attributes.

Example:

In the following example, we create two instance variables, name and age, in the Student class.

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

# create first object
s1 = Student("Jessa", 20)

# access instance variable
print('Object 1')
print('Name:', s1.name)
print('Age:', s1.age)

# create second object
s2 = Student("Kelly", 10)

# access instance variable
print('Object 2')
print('Name:', s2.name)
print('Age:', s2.age)
Code language: Python (python)

Output

Object 1
Name: Jessa
Age: 20
Object 2
Name: Kelly
Age: 10

Note:

  • When we created each object, we passed values for its instance variables to the constructor.
  • Each object holds different values because we passed different values to the constructor.
  • Variables declared directly in the class body (outside __init__() and other methods) belong to the class. They’re shared by all instances.

Modify Values of Instance Variables

We can modify the value of an instance variable by assigning a new value to it using the object reference.

Note: When you change an instance variable of one object, the change isn’t reflected in the other objects, because every object maintains its own copy of the instance variable.

Example

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

# create object
stud = Student("Jessa", 20)

print('Before')
print('Name:', stud.name, 'Age:', stud.age)

# modify instance variable
stud.name = 'Emma'
stud.age = 15

print('After')
print('Name:', stud.name, 'Age:', stud.age)Code language: Python (python)

Output

Before
Name: Jessa Age: 20
After
Name: Emma Age: 15

Ways to Access Instance Variable

Besides using object.variable from outside the class, there are two common ways to access an instance variable:

  • Inside the class, in an instance method, using the object reference (self)
  • Using the built-in getattr() function

Example 1: Access instance variable in the instance method

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

    # instance method access instance variable using self
    def show(self):
        print('Name:', self.name, 'Age:', self.age)

# create object
stud = Student("Jessa", 20)

# call instance method
stud.show()
Code language: Python (python)

Output

Name: Jessa Age: 20
instance variables and methods
instance variables and methods

Example 2: Access instance variable using getattr()

getattr(object, 'instance_variable', default)Code language: Python (python)

Pass the object reference and the instance variable name (as a string) to getattr() to get the value of an instance variable. The optional third argument is a default value returned when the attribute doesn’t exist. Without it, a missing attribute raises an AttributeError.

getattr() is useful when the attribute name is stored in a variable, for example when it comes from user input or a config file.

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

# create object
stud = Student("Jessa", 20)

# Use getattr instead of stud.name
print('Name:', getattr(stud, 'name'))
print('Age:', getattr(stud, 'age'))Code language: Python (python)

Output

Name: Jessa
Age: 20

Check and Set Instance Variables: hasattr() and setattr()

Python provides two more built-in functions that work with attributes by name:

  • hasattr(object, name): Returns True if the object has the attribute, otherwise False.
  • setattr(object, name, value): Sets the attribute to the given value. If the attribute doesn’t exist, it is created.

Example:

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

stud = Student("Jessa", 20)

# getattr with a default value
print('Marks:', getattr(stud, 'marks', 'Not available'))

# check if an attribute exists
print(hasattr(stud, 'name'))
print(hasattr(stud, 'marks'))

# set (add or modify) an attribute by name
setattr(stud, 'marks', 85)
print('Marks:', stud.marks)

# vars() returns the same dictionary as __dict__
print(vars(stud))Code language: Python (python)

Output:

Marks: Not available
True
False
Marks: 85
{'name': 'Jessa', 'age': 20, 'marks': 85}

Instance Variables Naming Conventions

According to the PEP 8 style guide:

  • Instance variable names should be all lowercase. For example, id.
  • Separate words in an instance variable name with an underscore. For example, store_name.
  • Non-public instance variables should begin with a single underscore. For example, _salary.
  • If an instance variable name needs to be mangled (to avoid name clashes in subclasses), begin it with two underscores. For example, __salary. See Encapsulation in Python.

Dynamically Add Instance Variable to a Object

We can add an instance variable to a particular object from outside the class. Use the following syntax to add a new instance variable to an object.

object_reference.variable_name = valueCode language: Python (python)

Example:

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

# create object
stud = Student("Jessa", 20)

print('Before')
print('Name:', stud.name, 'Age:', stud.age)

# add new instance variable 'marks' to stud
stud.marks = 75
print('After')
print('Name:', stud.name, 'Age:', stud.age, 'Marks:', stud.marks)
Code language: Python (python)

Output

Before
Name: Jessa Age: 20
After
Name: Jessa Age: 20 Marks: 75

Note:

  • A variable added this way exists only on that one object, not on the class or on other objects.
  • Adding an instance variable to one object isn’t reflected in the other objects, because every object has a separate set of instance variables.
  • Adding attributes outside the class makes code harder to follow. Prefer creating all instance variables in __init__().

Dynamically Delete Instance Variable

In Python, we use the del statement or the delattr() function to delete an attribute of an object. Both do the same thing.

  • del statement: Deletes a name or reference. It can delete variables, list items, dictionary keys, and object attributes, for example del s1.name.
  • delattr() function: Deletes an attribute by name. It’s useful when the attribute name is stored in a string.

Note: If we try to access a deleted attribute, Python raises an AttributeError.

Example 1: Using the del statement

class Student:
    def __init__(self, roll_no, name):
        # Instance variable
        self.roll_no = roll_no
        self.name = name

# create object
s1 = Student(10, 'Jessa')
print(s1.roll_no, s1.name)

# del name
del s1.name
# Try to access name variable
print(s1.name)
Code language: Python (python)

Output

10 Jessa
AttributeError: 'Student' object has no attribute 'name'

Example 2: Using the delattr() function

The delattr() function deletes the named attribute from the object. Use the following syntax.

delattr(object, name)Code language: Python (python)
  • object: The object whose attribute we want to delete.
  • name: The name of the instance variable to delete, as a string.

Example

class Student:
    def __init__(self, roll_no, name):
        # Instance variable
        self.roll_no = roll_no
        self.name = name

    def show(self):
        print(self.roll_no, self.name)

s1 = Student(10, 'Jessa')
s1.show()

# delete instance variable using delattr()
delattr(s1, 'roll_no')
s1.show()
Code language: Python (python)

Output

10 Jessa
AttributeError: 'Student' object has no attribute 'roll_no'

Access Instance Variable From Another Class

We can access the instance variables of one class from another class using an object reference. This is common with inheritance in Python, when a child class needs to use instance variables that the parent class created.

Let’s understand this with the help of an example.

In this example, engine is an instance variable of the Vehicle class. The Car class inherits from Vehicle and calls its constructor with super().__init__(), so a Car object also gets the engine instance variable.

class Vehicle:
    def __init__(self):
        self.engine = '1500cc'

class Car(Vehicle):
    def __init__(self, max_speed):
        # call parent class constructor
        super().__init__()
        self.max_speed = max_speed

    def display(self):
        # access parent class instance variables 'engine'
        print("Engine:", self.engine)
        print("Max Speed:", self.max_speed)

# Object of car
car = Car(240)
car.display()
Code language: Python (python)

Output

Engine: 1500cc
Max Speed: 240

List all Instance Variables of a Object

We can get all the instance variables of an object using its __dict__ attribute (or the built-in vars() function, which returns the same thing).

__dict__ is a dictionary that holds each instance variable’s name as the key and its value as the value.

Example:

class Student:
    def __init__(self, roll_no, name):
        # Instance variable
        self.roll_no = roll_no
        self.name = name

s1 = Student(10, 'Jessa')
print('Instance variable object has')
print(s1.__dict__)

# Get each instance variable
for name, value in s1.__dict__.items():
    print(name, '=', value)
Code language: Python (python)

Output:

Instance variable object has
{'roll_no': 10, 'name': 'Jessa'}
roll_no = 10
name = Jessa

Instance Variable vs Class Variable With the Same Name

When you read object.attribute, Python first looks in the object’s own instance variables, and only then in the class. So if you assign to a class variable through an object, Python doesn’t change the class variable. It creates a new instance variable with the same name on that object only, which hides (shadows) the class variable for that object.

class Student:
    # class variable
    school_name = 'ABC School'

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

s1 = Student('Jessa')
s2 = Student('Kelly')

# creates a NEW instance variable on s1 only
s1.school_name = 'XYZ School'

print(s1.school_name)
print(s2.school_name)
print(Student.school_name)
print(s1.__dict__)
print(s2.__dict__)Code language: Python (python)

Output:

XYZ School
ABC School
ABC School
{'name': 'Jessa', 'school_name': 'XYZ School'}
{'name': 'Kelly'}

To change a class variable for all objects, assign it through the class name, for example Student.school_name = 'XYZ School'. Learn more in Python Class Variables.

Summary

  • Instance variables belong to an object, and every object has its own copy.
  • Create instance variables in __init__() using self.name = value.
  • Access them with object.name outside the class and self.name inside instance methods.
  • Use getattr(), setattr(), hasattr(), and delattr() to work with attributes by name.
  • Use del object.name or delattr() to delete an instance variable.
  • Use __dict__ or vars() to list all instance variables of an object.
  • Assigning to a class variable through an object creates a new instance variable instead of changing the class variable.

Filed Under: Python, Python Object-Oriented Programming (OOP)

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Object-Oriented Programming (OOP)

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python Object-Oriented Programming (OOP)
TweetF  sharein  shareP  Pin

  Python OOP

  • Python OOP
  • Classes and Objects in Python
  • Constructors in Python
  • Python Destructors
  • Encapsulation in Python
  • Polymorphism in Python
  • Inheritance in Python
  • Python Instance Variables
  • Python Instance Methods
  • Python Class Variables
  • Python Class Method
  • Python Static Method
  • Python Class Method vs. Static Method vs. Instance Method
  • Python OOP exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com