How to Add a Method to an Existing Class in Python

3/20/2021

How To

1. Identify the class of interest

This is the class you want to “extend” / where you want to add the method.

Example - A class you already created:

# Python
class BoringClass:
    """
    This class currently does nothing
    """
    pass

Example - A class created by someone else:

# Python
from pandas import DataFrame

2. Write the method you want to add as a function

Note, as with any normal method, you will need to include self as the first input to the function

# Python
def say_hello(self, n=2):
    for _ in range(n):
        print("Hello world!")

3. Assign your method to the class of interest

Example - A class you already created:

# Python
BoringClass.say_hello = say_hello

Example - A class created by someone else:

# Python
DataFrame.say_hello = say_hello

4. Try it out!

Example - A class you already created:

# Python
bc = BoringClass()
bc.say_hello(n=1)

Hello world!

Example - A class created by someone else:

# Python
df = DataFrame([])
df.say_hello(n=3)

Hello world!
Hello world!
Hello world!

Tested On

Sources

  1. https://stackoverflow.com/questions/972/adding-a-method-to-an-existing-object-instance

Like This?

for More in the Future

with Comments / Questions / Suggestions