0

I wonder if anything like this is possible in Python. Say that in a library, there is a class X defined with methods a, b and c:

class X:
  def a(self):
     ...
  def b(self):
     ...
  def c(self):
     ...

I would like to add a method custom into the class X (so that I can then call X().custom()) without modifying the library code.

I know I could do something like

def custom(self):
   ...
X.custom = custom

but doing it this way does not look very nice.

Is there any more intelligent way of achieving what I want (for example similar to impl on structs in Rust)?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
karlosss
  • 2,435
  • 6
  • 24
  • 39

1 Answers1

2

If you are using python3, import the library then expand the class as explained below- Assuming the parent code (where class X is written) was in main.py then we can do something like this -

import main

class X(main.X):

    def custom():
        print("hello hi")
        #your code

For details, you may refer- How to extend a class in python?

cshelly
  • 417
  • 1
  • 10