What is instance variable in python

Python Instance Variables

Summary: in this tutorial, you’ll learn about Python instance variables including data variables and function variables.

Introduction to the Python instance variables

In Python, class variables are bound to a class while instance variables are bound to a specific instance of a class. The instance variables are also called instance attributes.

The following defines a HtmlDocument class with two class variables:

from pprint import pprint class HtmlDocument: version = 5 extension = 'html' pprint(HtmlDocument.__dict__) print(HtmlDocument.extension) print(HtmlDocument.version)Code language: Python (python)
mappingproxy('__dict__': '__dict__' of 'HtmlDocument' objects>, '__doc__': None, '__module__': '__main__', '__weakref__': '__weakref__' of 'HtmlDocument' objects>, 'extension': 'html', 'version': 5>)Code language: Python (python)

The HtmlDocument class has two class variables: extension and version . Python stores these two variables in the __dict__ attribute.

When you access the class variables via the class, Python looks them up in the __dict__ of the class.

Читайте также:  Svg and html elements

The following creates a new instance of the HtmlDocument class:

home = HtmlDocument()Code language: Python (python)

The home is an instance of the HtmlDocument class. It has its own __dict__ attribute:

pprint(home.__dict__)Code language: Python (python)

The home.__dict__ is now empty:

<>Code language: Python (python)

The home.__dict__ stores the instance variables of the home object like the HtmlDocument.__dict__ stores the class variables of the HtmlDocument class.

Unlike the __dict__ attribute of a class, the type of the __dict__ attribute of an instance is a dictionary. For example:

print(type(home.__dict__))Code language: Python (python)
class 'dict'>Code language: Python (python)

Since a dictionary is mutable, you can mutate it e.g., adding a new element to the dictionary.

Python allows you to access the class variables from an instance of a class. For example:

print(home.extension) print(home.version)Code language: Python (python)

In this case, Python looks up the variables extension and version in home.__dict__ first. If it doesn’t find them there, it’ll go up to the class and look up in the HtmlDocument.__dict__ .

However, if Python can find the variables in the __dict__ of the instance, it won’t look further in the __dict__ of the class.

The following defines the version variable in the home object:

home.version = 6Code language: Python (python)

Python adds the version variable to the __dict__ attribute of the home object:

print(home.__dict__)Code language: Python (python)

The __dict__ now contains one instance variable:

'version': 6>Code language: Python (python)

If you access the version attribute of the home object, Python will return the value of the version in the home.__dict__ dictionary:

print(home.version)Code language: Python (python)
6Code language: Python (python)

If you change the class variables, these changes also reflect in the instances of the class:

HtmlDocument.media_type = 'text/html' print(home.media_type)Code language: Python (python)
text/htmlCode language: Python (python)

Initializing instance variables

In practice, you initialize instance variables for all instances of a class in the __init__ method.

For example, the following redefines the HtmlDocument class that has two instance variables name and contents

class HtmlDocument: version = 5 extension = 'html' def __init__(self, name, contents): self.name = name self.contents = contentsCode language: Python (python)

When creating a new instance of the HtmlDocument , you need to pass the corresponding arguments like this:

blank = HtmlDocument('Blank', '')Code language: Python (python)

Summary

  • Instance variables are bound to a specific instance of a class.
  • Python stores instance variables in the __dict__ attribute of the instance. Each instance has its own __dict__ attribute and the keys in this __dict__ may be different.
  • When you access a variable via the instance, Python finds the variable in the __dict__ attribute of the instance. If it cannot find the variable, it goes up and look it up in the __dict__ attribute of the class.

Источник

Instance Variables in Python Programming

In this lesson, we will understand what is Instance Variable in Python Programming and how to create them along with some examples.

What are Instance Variables in Python?

We use Instance Variables to store values in an object. Each object has its own copy of instance variables that are not shared between other objects.

Instance variables are declared and initialized inside a unique method called Constructor. The first parameter of the constructor method is self which refers to the memory address of the instance (object) of the current class. Using self, we can access and modify the value of the instance variables of a class.

In python, the constructor is created with the __init__() method, which automatically gets executed when we create an object of a class.

video-poster

Example of creating Instance Variables using Constructor Method

class Record: # Creating instance variables using constructor method def __init__(self): self.name = "" self.age = 0 # Creating an object x of the class Record x = Record()

In the above example, we have created two instance variables, name and age, and initialized their values as blank and 0, respectively. After that, we created an object x of the class Record.

We can also initialize the instance variables of a class at the time of creating an object by passing values to the parameterized constructor method. A parameterized constructor method takes more than one argument. See the example given below.

Example of creating and initializing Instance Variables using Parameterized Constructor Method

class Record: # Creating instance variables using parameterized constructor method def __init__(self, name, age): self.name = name self.age = age # Creating an object x of the class Record x = Record('Peter', 22)

In the above program, we are sending Peter and 22 as the values for the name and age variables of the parameterized constructor method. Then the values get initialized from name and age parameter variables to the class’s name and age instance variables.

Note: It’s not compulsory to have identical names for both parameter and instance variables, and we can use different names for parameter variables in parameterized constructors. See the example given below.

Parameterized Constructor Example 2

class Record: # Creating instance variables using parameterized constructor method def __init__(self, nm, ag): self.name = nm self.age = ag # Creating an object x of the class Record x = Record('Peter', 22)

Access and Modify Values of Instance Variables

We can access the value of an instance variable in two ways, first by using the object of the class followed by a dot (.) operator and then writing the name of the instance variable whose value we want to access, and second by using the getattr() function.

We can modify the value of an instance variable by using the object of the class followed by a dot (.) operator and then writing the name of the instance variable with an equal sign and then providing the new value to it or by using the setattr() function.

Syntax of getattr and setattr function

getattr(object_name, 'instance_variable_name') setattr(object_name, 'instance_variable_name', value)

Note: The value should be enclosed within single or double quotes if the value is a string.

Access and Modify Instance Variables using dot operator

class Record: # Creating instance variables using parameterized constructor method def __init__(self, nm, ag): self.name = nm self.age = ag # Creating an object x of the class Record x = Record('Peter', 22) # Values of instance variables before modification print('Name: %s' %(x.name)) print('Age: %d' %(x.age)) # Modify the values of the instance variables x.name = 'Thomas' x.age = 25 # Values of instance variables after modification print('Name: %s' %(x.name)) print('Age: %d' %(x.age))

Output

Name: Peter Age: 22 Name: Thomas Age: 25

Access and Modify Instance Variables using getattr and setattr functions

class Record: # Creating instance variables using parameterized constructor method def __init__(self, nm, ag): self.name = nm self.age = ag # Creating an object x of the class Record x = Record('Peter', 22) # Values of instance variables before modification print('Name:', getattr(x, 'name')) print('Age:', getattr(x, 'age')) # Modify the values of the instance variables setattr(x, 'name', 'Thomas') setattr(x, 'age', 25) # Values of instance variables after modification print('Name:', getattr(x, 'name')) print('Age:', getattr(x, 'age'))

Output

Name: Peter Age: 22 Name: Thomas Age: 25

Get a list of all the Instance Variables of an Object

We can get a list of all the instance variables of an object in the form of a dictionary using the function __dict__.

Example

class Record: # Creating instance variables using parameterized constructor method def __init__(self, nm, ag): self.name = nm self.age = ag # Creating an object x of the class Record x = Record('Peter', 22) # Display the list of all the instance variables of the object x print(x.__dict__)

Output

Add New Instance Variable Dynamically to an Object

We can dynamically add a new instance variable to an object by writing the object name followed by a dot (.) operator and then writing the new name of the instance variable with an equal sign and then providing the new value. The newly added instance variable is only available in the object it has been added to. The newly added instance variable is not reflected in other objects of the same class.

Example

class Record: # Creating instance variables using parameterized constructor method def __init__(self, nm, ag): self.name = nm self.age = ag # Creating two object x, y of the class Record x = Record('Peter', 22) y = Record('Thomas', 25) # Add a new instance variable to object x x.roll=1 # Display the list of all the instance variables of the object x print(x.__dict__) # Display the list of all the instance variables of the object y print(y.__dict__)

Output

Delete an Instance Variable Dynamically from an Object

We can dynamically delete an instance variable from an object using the del statement or delattr() function. The del statement or delattr() function will delete the instance variable only from the object it applied on and not from all the objects.

Syntax of delattr function

delattr(object_name, 'instance_variable_name')

Example

class Record: # Creating instance variables using parameterized constructor method def __init__(self, rn, nm, ag): self.rollno = rn self.name = nm self.age = ag # Creating two object x, y of the class Record x = Record(1,'Peter', 22) y = Record(2,'Thomas', 25) # Delete the instance variable rollno from object x delattr(x,'rollno') # Display the list of all the instance variables of the object x print(x.__dict__) # Display the list of all the instance variables of the object y print(y.__dict__)

Источник

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