Class Methods in Python

Class Methods in Python

Kishore V


Class Methods in Python

Methods are functions defined inside a class.

They describe the actions or behavior of objects created from that class.

Each method automatically receives the current object through the self parameter.

Defining a Method in a Class

Methods are created just like functions, but they are placed inside a class.

Example: Simple Class Method

Output:

Hi, I am Ananya
Try it Yourself

Note: self must always be the first parameter of an instance method.

Methods with Parameters

Methods can accept additional parameters, just like normal functions.

Example: Method with Arguments

Output:

6
32
Try it Yourself

Methods Accessing Object Properties

Methods can read object data using self.

Example: Access Properties Inside a Method

Output:

Riya lives in India
Try it Yourself

Methods Modifying Object Properties

Methods can also update the values of object properties.

Example: Modify a Property

Output:

Current value: 1
Current value: 2
Try it Yourself

The __str__() Method

The __str__() method defines what should be displayed when an object is printed.

Example: Without __str__()

Output:

<__main__.Device object at 0x7f8b9a1c2d30>
Try it Yourself

Example: With __str__()

Output:

Device Name: Router
Try it Yourself

Using Multiple Methods in a Class

A class can contain multiple methods that work together to perform tasks.

Example: Multiple Methods Working Together

Output:

Task added: Study Python
Task added: Practice OOP
Tasks:
- Study Python
- Practice OOP
Try it Yourself

Deleting Methods from a Class

You can remove a method from a class using the del keyword. This affects all objects of that class.

This is rarely used in real-world programs.

Example: Delete a Class Method

Output:

Error: 'Demo' object has no attribute 'show'
Try it Yourself

Our website uses cookies to enhance your experience. Learn More
Accept !