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.

Declare Instance variable in Python
Declare Instance variable

Create Instance Variables

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.

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 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

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

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

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

    # instance method access instance variable
    def show(self):
        print('Name:', stud.name, 'Age:', stud.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')Code language: Python (python)

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

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

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:

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:

  • 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

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'

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

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 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

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 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:

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 key_value in s1.__dict__.items():
    print(key_value[0], '=', key_value[1])
Code language: Python (python)

Output:

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

roll_no = 10
name = Jessa

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

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

Comments

  1. AM says

    November 1, 2024 at 9:55 pm

    Correction in “Ways to Access Instance Variable”

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

    # instance method access instance variable
    def show(self):
    print(‘Name:’, stud.name, ‘Age:’, stud.age)
    “`

    We should use “self.name” and “self.age” in the class method show().

    Reply
  2. Anita Yadav says

    May 25, 2023 at 8:59 am

    Instance variables: If the value of a variable varies from object to object, then such variables are called instance variables. can I get the example pls?

    Reply
    • Vedant Parekh says

      November 7, 2023 at 4:04 pm

      class Vehicle:
      def __init__(self, name, Mileage):
      self.name = name
      self.Mileage = Mileage

      Vehicle1 = Vehicle(“Volvo”, 18)
      print(“Name:”, Vehicle1.name, “\nMileage:”, Vehicle1.Mileage)

      Vehicle2 = Vehicle(“Audi”, 25)
      print(“\nName:”, Vehicle2.name, “\nMileage:”, Vehicle2.Mileage)

      Reply
  3. Li Weidong says

    February 27, 2023 at 8:09 am

    “Use the __dict__ function of an object to get all instance variables along with their value.”

    I think that the __dict__ is not a function of an object, but an attribute. It’s a dict.

    Reply
  4. O says

    October 25, 2022 at 10:57 pm

    Quick thought,

    In teaching this, I often find that there is confusion between the ideas of an object and an instance. Everything in python is an object, but not everything is an instance. A local variable is an object, a function is an object. As counterintuitive to OO thinking it may sound, maybe we should minimize using the word object and use more clear definite language. Instance Variable, Instance Method, etc

    Current: Instance variables: If the value of a variable varies from object to object, then such variables are called instance variables.

    Suggested: Instance variables: If the value of a variable varies from Instance to Instance, then such variables are called instance variables.

    Reply
    • O says

      October 25, 2022 at 11:02 pm

      Suggested: Instance variables: If the value of a variable varies from Instance to Instance, then such variables are called instance variables and are declared in the __init__ function(constructor).

      I do recognize that you use these terms throughout, but I personally think the addition of the word object is not required for understanding your lesson.

      Reply
  5. ashish arora says

    April 27, 2022 at 7:59 pm

    Hello Vishal Ji,

    I was literally finding this answer only. and now it is clear. I read many articles but nobody said this simple thing…which is hitting me for hours. I just wanted to clear this doubt so desperately and here it is.

    let me take to you to the thought I was struck at.

    ***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 in the remaining objects because every object has a separate copy of the instance variable.

    Btw my question was that if we do not pass anything in a class definition about the instantiation of attributes of an instance of class then during dynamically creation of a variable using the reference of an object, will it take self as a first parameter or not.

    Now it is clear with the above note which you mentioned in your article.

    That in class it won’t do anything.
    Only in the object, it will be present and will be stored in the __dict__ of that object only.
    We can not reference it using the class itself.

    my code of checking it:

    class Robot:    #during the defining of class we didn't create attributes of the instances of the class
        pass
    
    x = Robot()
    y = Robot() 
    x.name = "Marvin"
    x.build_year = 98 #however we explicitaly did outside.
    y.name = "Caliban"  #this method is less used and leads to confusion
    y.build_year = "1993"
    print(x.name)
    print(x.build_year)

    output:

    Marvin
    98

    x.__dict__
    output:

    {'name': 'Marvin', 'build_year': 98}

    Robot.build_year(x)
    output:

    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
     in 
    ----> 1 Robot.build_year(x)
    
    AttributeError: type object 'Robot' has no attribute 'build_year'

    But is there any concept like object inheritance?

    then my following question on that thing..how does data get stored in __dict__ who instructs them to form dict, why did they not form a list or in any data structure.

    Secondly, does self parameter will be instantiated for that instance we created a variable using referencing it.

    hope you understand. kindly take the time to answer them.

    Thanks, Ashish

    Reply
  6. Fatih says

    November 26, 2021 at 5:33 pm

    A minor correction: “Self” is not a keyword. Conventionally, python users have been using the word “self”, but we are allowed to use a different name instead of it. Though, it is not recommended.

    By the way, great site. Thanks!

    Reply
    • syed says

      March 18, 2022 at 1:58 am

      Amazing work
      Brilliant

      Reply
  7. Hyuk Cho says

    October 15, 2021 at 7:59 am

    Vishal,

    It is just a minor correction to avoid any potential confusion.
    Under “Create Instance Variables”, the first sentence could be confusing the readers because of the word “class”.
    CURRENT: Instance variables are declared inside a CLASS method using the self keyword.
    SUGGESTED: Instance variables are declared inside a method using the self keyword.

    Thanks,

    HC

    Reply
    • Vishal says

      October 21, 2021 at 4:37 pm

      Hey Hyuk Cho, Thank you for your observation and suggestions. I have updated the article.

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

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 for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

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

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