Python Adding New Functionalities Smartly

Python is a flexible and dynamic programming language that allows you to modify or extend its features without changing the original code. Here are some common ways to add new functionalities smartly in Python:

You can use setattr() to dynamically add methods or attributes to a class or an object. For example:


class Foo:

    def __init__(self, v):
        self.v = v

def my_new_method(self):
    print("self.v =", self.v)


# Add a new method to the Foo class
setattr(Foo, "print_v", my_new_method)

# Call the new method on an instance of Foo
Foo(5).print_v()
This will print self.v = 5.


You can use decorators to wrap a function or a class with another function that adds some extra functionality. For example:


def average(func):
    # A decorator function that calculates the average of two numbers
    def wrapper(*args, **kwargs):
        # Call the original function and get the result
        result = func(*args, **kwargs)
        # Calculate the average and return it
        return result / 2
    return wrapper


@average
def add(a, b):

    # A function that calculates the sum of two numbers
    return a + b

# Call the decorated function
print(add(10, 20))
# This will print 15.0, which is the average of 10 and 20.


You can create a new module that imports an existing module and adds some new features or overrides some existing ones. For example:

# A new module named newmod.py that extends an existing module named mod.py

# Import everything from mod.py
from mod import *

# Define a new function that does something different

def foo():
    print("This is foo from newmod")


# Override an existing function from mod.py with a new implementation
def bar():
    print("This is bar from newmod")


Then you can import your new module instead of the original one and use its features.

# Adding Average Functionality to a Function That Calculates Percentage and Total With The Help Of Decorator

import functools
def decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        numbers = list(args)
        print("Percentage: ",((sum(numbers)*100)/len(numbers)))
        result = func(*args,**kwargs)
        print("Total: ",sum(numbers) )
        return result
    return wrapper

@decorator
def average(*numbers):
    return sum(list(numbers))/len(list(numbers))
result = average(77,89,93,96)
print("Average: ", result)


# output
# Percentage:  8875.0
#Total:  355
# Average:  88.75

I hope this helps you understand how to add new functionalities smartly in Python. Do you have any questions or feedback?

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions