Python define variable in class

Python Instance Variables Explained With Examples

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?

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.

Читайте также:  Где хранятся объекты java

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

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.

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) 
Object 1 Name: Jessa Age: 20 Object 2 Name: Kelly Age: 10
  • 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.

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

instance variables and methods

Example 2: Access instance variable using getattr()

getattr(Object, 'instance_variable')

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

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 = value
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) 
Before Name: Jessa Age: 20 After Name: Jessa Age: 20 Marks: 75
  • 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) 
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.

  • object : the object whose attribute we want to delete.
  • name : the name of the instance variable we want to delete from the object.
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() 
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() 
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

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]) 
Instance variable object has roll_no = 10 name = Jessa

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

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help 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 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Оцените статью