Changing the functionality of a function


#1

i have already finished this exercise but i was wondering if i can change the whole function by a function


#2

I'm not sure what do you mean.

Why would you make a whole new function to change another one, when you can just rewrite the code ?


#3

Hi, @letmeprogramyou1 ,

While the following is not a very useful example, it is offered to demonstrate that a function can redefine another function. Be careful, though, for changing the definition of a function in the midst of program execution can easily lead to buggy code.

def func():
    # original func
    return "I am the original func function."

def redefine_func():
    # Make the name func global; redefine the func function
    global func
    def func():
        return "I am the redefined func function."
    return "I redefined the func function."

# Call func
print(func())
# Call the function that redefines func
print(redefine_func())
# Call func again; see that it has changed
print(func())

Output ...

I am the original func function.
I redefined the func function.
I am the redefined func function.

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.