◐ Shell
clean mode source ↗

Python Instance Variables Explained With Examples

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

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.

Declare Instance variable in Python
Declare Instance variable

Instance variables are declared inside a method using the self keyword. We use a constructor to define and initialize the instance variables. Let’s see the example to declare an instance variable in Python.

Example:

In the following example, we are creating two instance variable name and age in the Student class.

Output

Object 1
Name: Jessa
Age: 20

Object 2
Name: Kelly
Age: 10

Note:

  • When we created an object, we passed the values to the instance variables using a constructor.
  • Each object contains different values because we passed different values to a constructor to initialize the object.
  • Variable declared outside __init__() belong to the class. They’re shared by all instances.

Modify Values of Instance Variables

We can modify the value of the instance variable and assign a new value to it using the object reference.

Note: When you change the instance variable’s values of one object, the changes will not be reflected in the remaining objects because every object maintains a separate copy of the instance variable.

Example

Output

Before
Name: Jessa Age: 20

After
Name: Emma Age: 15

Ways to Access Instance Variable

There are two ways to access the instance variable of class:

  • Within the class in instance method by using the object reference (self)
  • Using getattr() method

Example 1: Access instance variable in the instance method

Output

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

Example 2: Access instance variable using getattr()

getattr(Object, 'instance_variable')Code language: Python (python)

Pass the object reference and instance variable name to the getattr() method to get the value of an instance variable.

Output

Name: Jessa
Age: 20

Instance Variables Naming Conventions

  • Instance variable names should be all lower case. For example, id
  • Words in an instance variable name should be separated by an underscore. For example, store_name
  • Non-public instance variables should begin with a single underscore
  • If an instance name needs to be mangled, two underscores may begin its name

Dynamically Add Instance Variable to a Object

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

object_referance.variable_name = valueCode language: Python (python)

Example:

Output

Before
Name: Jessa Age: 20

After
Name: Jessa Age: 20 Marks: 75

Note:

  • We cannot add an instance variable to a class from outside because instance variables belong to objects.
  • Adding an instance variable to one object will not be reflected the remaining objects because every object has a separate copy of the instance variable.

Dynamically Delete Instance Variable

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

  • del statement: The del keyword is used to delete objects. In Python, everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list, etc.
  • delattr() function: Used to delete an instance variable dynamically.

Note: When we try to access the deleted attribute, it raises an attribute error.

Example 1: Using the del statement

Output

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

delattr() function

The delattr() function is used to delete the named attribute from the object with the prior permission of 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 we want to delete from the object.

Example

Output

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

Access Instance Variable From Another Class

We can access instance variables of one class from another class using object reference. It is useful when we implement the concept of inheritance in Python, and we want to access the parent class instance variable from a child class.

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

In this example, the engine is an instance variable of the Vehicle class. We inherited a Vehicle class to access its instance variables in Car class

Output

Engine: 1500cc
Max Speed: 240

List all Instance Variables of a Object

We can get the list of all the instance variables the object has. Use the __dict__ function of an object to get all instance variables along with their value.

The __dict__ function returns a dictionary that contains variable name as a key and variable value as a value

Example:

Output:

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

roll_no = 10
name = Jessa

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.

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