Tomer Smadja
Tomer Smadja

Reputation: 66

Python - Can I modify a method in runtime?

Is it possible to modify a method in runtime? Let's say I have a class A that has a method func1(some_param). Is it possible to modify this func1(some_param) method and let's say add a line print('HelloWorld') in the beginning?

I had some experiments with overriding this method by accessing it like this - A.func1 but got stuck in the stage of inserting a line into it.

Here is the example class

class A:
    def __init__(self, some_field):
        self.some_field = some_field
        
    def func1(self, param):
        self.some_field = param

And in runtime I want to achieve this class:

class A:
    def __init__(self, some_field):
        self.some_field = some_field
        
    def func1(self, param):
        print('HelloWorld')
        self.some_field = param

Upvotes: 0

Views: 605

Answers (2)

Aaj Kaal
Aaj Kaal

Reputation: 1274

Yes it is possible. Python is very dynamic in that sense

Code:

class A:
    def __init__(self, some_field):
        self.some_field = some_field
        
    def func1(self, param):
        self.some_field = param

def func2(self, param):
    print('HelloWorld')
    self.some_field = param        

def func1(self, param):
    print('stand alone func')
    self.some_field = param        
    
a = A('init')
a.func1('for func1')
A.func2 = func2
a.func2('for func2')

A.func1 = func1     # you know this is not good programming practice
a.func1('for new func1')

Output:

HelloWorld
stand alone func 

Upvotes: 0

user7837926
user7837926

Reputation:

If the only thing to do is insert line before or after you can use decorator, pass parameter to the decorator. see this article.

Upvotes: 1

Related Questions