3. Problem to create a Python class with instance method

In this Python oops program, we will create a Python class with instance method. The program creates a class with a constructor and methods to display and update the name attribute of an object. It creates an object, displays its initial name, updates the name, and then displays the updated name.

Python class with instance method

Steps to solve the program
  1. The code demonstrates how to create a Python class with instance method and variables for updating and displaying the value of an attribute.
  2. The constructor method __init__() is used to initialize the name instance variable when an object is created.
    The display_name() method allows us to print the value of the name instance variable.
  3. The update_name() method provides a way to update the value of the name instance variable by passing a new name as a parameter.
  4. By combining these methods, we can create objects of the MyClass class, set and update the name attribute, and display the updated name whenever needed. In the example, the name is initially set to “Omkar” and then updated to “Ketan”.
				
					class MyClass:
    def __init__(self, name):
        self.name = name
    
    def display_name(self):
        print("Name:", self.name)
    
    def update_name(self, new_name):
        self.name = new_name

# Create an object of the class
obj = MyClass("Omkar")
obj.display_name()

obj.update_name("Ketan")
obj.display_name()
				
			

Output:

				
					Name: Omkar
Name: Ketan
				
			

Related Articles

create a class with an instance variable.

create a class with class variables.

Leave a Comment