Python Instance Variables

Instance variables belong to instances of a class. Each instance has its own copy of instance variables. Instance variables are declared inside methods and you must prefix them with self. otherwise, you will by mistake create local variables. It is recommended to declare instance variables inside constructors.

#Python Program to create instance variables
class Person:
  def __init__(self, first, last):
    self.firstName = first
    self.lastName = last

p = Person('Mitali', 'Natani')
print('First Name: ', p.firstName)
print('Last Name: ', p.lastName)

Output of the above program

First Name: Mitali
Last Name: Natani

Note: Class and static methods cannot access instance variables. Outside the class, you can access instance variables only through objects and not with classname.

Possible mistakes while dealing with instance variables

1. Creating instance variables without using self.

class Person:

  def firstName(self, first):
    firstName = first

p = Person()
print('First Name: ', p.firstName)

When you run the above program, you will get an error because you are trying to access local variables. So to solve this error, use self. while declaring variable firstName.

2. Accessing instance variable using classname.

class Person:
  def __init__(self, first):
    self.firstName = first

p = Person('Mitali')
print('First Name: ', Person.firstName)

When you run the above program, you will get AttributeError because you are accessing instance variable firstName using class name(Person).