add method to class in python

In Python, you can add a new method to a class using the following syntax:

main.py
class ClassName:
    def existing_method(self):
        # existing method code

    def new_method(self):
        # new method code
132 chars
7 lines

Here, new_method is added to the class ClassName. It takes self as its first argument, which refers to the instance of the class that the method is called on. You can then write the code for the new method inside the function block.

You can then create an object of this class and call the new method:

main.py
# create object of the class
object_name = ClassName()

# call the new method
object_name.new_method()
103 chars
6 lines

This will execute the code written in the new_method function block.

related categories

gistlibby LogSnag