Skip to content

Python class instance variables

  • by

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 or suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading