Python class instance variables

In the Python class, if variables values are assigned inside methods are called instance variables. Instance variables can have different values across multiple instances of a class.

Python class instance variables example

Simple example code declared Instance variables inside a class method and print the values after creating an object.

Create an instance of our class with the following values:

class Students:
    def __init__(self, name, age):
        self.name = name
        self.age = age


new_stu = Students("John", 15)
print(new_stu.name)
print(new_stu.age)

Output:

Python class instance variables

Modify Values of Instance Variables

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


# create object
stud = Student("John", 15)
print('Name:', stud.name, 'Age:', stud.age)

# modify instance variable
stud.name = 'Emma'
stud.age = 15

print('Name:', stud.name, 'Age:', stud.age)

Output:

Name: John Age: 15
Name: Emma Age: 15

Do comment if you have any doubts and suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.