-1

How to add a method to a class from another file in python? For example I have class main in file main.py and I have function something in file method.py. How could I make it so that class main has function something as a method?

martineau
  • 119,623
  • 25
  • 170
  • 301
Hexye
  • 49
  • 5

2 Answers2

2

you need to add it dynamically (here an example where all your data are in the same file)

def function(p): return p

class A:
   def __init__(self): pass

# add as instance method
setattr(A, 'function', lambda  self, p: function(p))
# add as class method
setattr(A, 'function_cls', classmethod(lambda cls, p: function(p)))
# # add as static method
setattr(A, 'function_static', staticmethod(lambda p: function(p)))

print(a.function('p'))
print(a.function.__class__)

print(A.function_cls('p'))
print(A.function_cls.__class__)

print(A.function_static('p'))
print(A.function_static.__class__)

Output

p
<class 'method'>
p
<class 'method'>
p
<class 'function'>

The difference is that class and static methods can also be called from an instance as from a class

cards
  • 3,936
  • 1
  • 7
  • 25
  • Thanks for the answer :) – Hexye Aug 20 '21 at 22:47
  • you can also change its name by changing the string parameter of setattr – cards Aug 20 '21 at 22:48
  • If i should do something like a function that needs self parameter? like if it should return self.dosomething()? – Hexye Aug 20 '21 at 22:51
  • self it is the price you have to pay to cast a function into a method, it carries the info of the instance. Try to remove it... and you get an error! – cards Aug 20 '21 at 22:52
  • so i can only use static methods in that way? – Hexye Aug 20 '21 at 22:53
  • updated answer now – cards Aug 20 '21 at 23:01
  • That technique to add methods to an existing class is sometimes called monkey patching. You can add instance methods, but then the function you use has to take a 'self' parameter. – Chris Aug 20 '21 at 23:06
  • @Chris monkey patching is about evaluating string which contains commands, this should be just dynamic stuffs – cards Aug 20 '21 at 23:12
0

You can do the monkey patch by assigning a function to a member name of the class:

class Main:
    def existing(self): print(f"existing in {type(self)}")

# monkey patch (can be in another file)
def something(self): print(f"something in {type(self)}")
Main.something = something


aMain = Main()

aMain.existing()
aMain.something()

existing in <class '__main__.Main'>
something in <class '__main__.Main'>

This will also work in subclasses:

class Sub(Main):
    def other(self): print(f"other in  {type(self)}")

aSub  = Sub()
aSub.existing()
aSub.other()
aSub.something()

existing in <class '__main__.Sub'>
other in  <class '__main__.Sub'>
something in <class '__main__.Sub'>
Alain T.
  • 40,517
  • 4
  • 31
  • 51