1

I am using a class A from an open-source library.

I want to add a function fn to A without changing the source of the library, so let's say the function fn is available only in my project.

Is it possible? If so, how could I do that?

Thanks

2
  • Add a function to A: can you please clarify with a small example? E.g. do you want to add a method, a class method, or something else? What have you tried? Commented Aug 16, 2018 at 9:14
  • You have to modify the opensource class method or Add new method in particular opensource class Commented Aug 16, 2018 at 9:33

2 Answers 2

2

If you want to add a method to one class the I think proper way to do that is to create class B that inherits from class A and there you can add the method. Something like

import open_source_library

class B(open_source_library.A):
    def my_fn():
         .....
Sign up to request clarification or add additional context in comments.

Comments

1

Problem

# a.py module
def print_message(msg):
    print(msg)

# b.py module
from a import print_message
def execute():
    print_message("Hello")

# c.py module which will be executed
import b
b.execute()

Answer

import a

def _new_print_message(message):
    print("NEW: " + message)

a.print_message = _new_print_message

import b
b.execute()

You have to first import a, then override the function and then import b so that it would use the a module that is already imported (and changed).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.