PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C 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: October 21, 2021 | 11 Comments

There are several kinds of variables in Python:

  • Instance variables in a class: these are called fields or attributes of an object
  • Local Variables: Variables in a method or block of code
  • Parameters: Variables in method declarations
  • Class variables: This variable is shared between 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, then such variables are called instance variables.
  • Class Variables: A class variable is a variable that is declared inside of class, but outside of any instance method or __init__() method.

After reading this article, you’ll learn:

  • How to create and access instance variables
  • Modify values of instance variables
  • How to dynamically add or delete instance variables
  • Scope of a instance variables

Table of contents

  • What is an Instance Variable in Python?
  • Create Instance Variables
  • Modify Values of Instance Variables
  • Ways to Access Instance Variable
  • Dynamically Add Instance Variable to a Object
  • Dynamically Delete Instance Variable
  • Access Instance Variable From Another Class

What is an Instance Variable in Python?

If the value of a variable varies from object to object, then such variables are called instance variables. For every object, a separate copy of the instance variable will be created.

Instance variables are not shared by objects. Every object has its own copy of the instance attribute. This means that for each object of a class, the instance variable value is different.

When we create classes in Python, instance methods are used regularly. we need to create an object to execute the block of code or action defined in the instance method.

Instance variables are used within the instance method. We use the instance method to perform a set of actions on the data/value provided by the instance variable.

We can access the instance variable using the object and dot (.) operator.

In Python, to work with an instance variable and method, we use the self keyword. We use the self keyword as the first parameter to a method. The self refers to the current object.