Why, there are so many ways to adjust a function? Let me know how many you’ve used in the comments section. 1 or 2 😊 😊

Click here and the code will run

1. Call the function directly (__call__)

The simplest and most direct way to use:

def func() :
    print('Hello, world! ')
func() # Hello, world!

func.__call__() # the same
Copy the code

2. Partial functions

Functools, Python’s built-in library, has a partial function that lets you fill in some of the arguments to a function and call it. It doesn’t seem to work, but it does when you run into it. 😊 😊

from functools import partial
# Please taste carefully!
def func(domain, user) :
    echo = f"Hello, {user}@{domain}!"
    print(echo)


func_userA = partial(func, user="userA")
func_userB = partial(func, user="userB")
func_userA("example.com") # Hello, [email protected]!
func_userB("example.com") # Hello, [email protected]!
Copy the code

3. The eval function

If you need to execute functions dynamically, you can use EVAL to execute dynamic code.

import sys
def pre_task() :
    print("running pre_task")

def task() :
    print("running task")

def post_task() :
    print("running post_task")

cmdList = ["pre_task()"."task()"."post_task()"]
for cmd in cmdList:
    eval(cmd) # execute function
# running pre_task
# running task
# running post_task
Copy the code

4. The getattr function

Run static methods in a class

import sys


class Task:
    @staticmethod
    def pre_task() :
        print("running pre_task")

    @staticmethod
    def task() :
        print("running task")

    @staticmethod
    def post_task() :
        print("running post_task")

#⚠️ string without parentheses.
cmdList = ["pre_task"."task"."post_task"]

task = Task()

for cmd in cmdList:
    func = getattr(task, cmd)
    func()
Copy the code

5. dictmethods

First, we need to know that every Python object has a built-in __dict__() method that returns a dictionary containing all the attributes of the object. In the following image, we can see all the attributes returned by the __dict__() method of list. Are those in the red box familiar to you?

class Task:
    @staticmethod
    def pre_task() :
        print("running pre_task")

    @staticmethod
    def task() :
        print("running task")

    @staticmethod
    def post_task() :
        print("running post_task")


func = Task.__dict__.get("pre_task")
func.__func__() # running pre_task
func() # Why not?
Copy the code

6. Globals function

import sys

def pre_task() :
    print("running pre_task")

def task() :
    print("running task")

def post_task() :
    print("running post_task")

cmdList = ["pre_task"."task"."post_task"]

for cmd in cmdList:
    func = globals().get(cmd)
    func()
# running pre_task
# running task
# running post_task
Copy the code

7. The exec function

You can define your function in a string, compile it into bytecode using the compile function, and then execute it using exec.

Way # 1
pre_task = """
print("running pre_task")
"""
exec(compile(pre_task, ' '.'exec'))
# running pre_task

Way # 2
with open('./source.txt') as f:
    source = f.read()
    exec(compile(source, 'source.txt'.'exec'))
Copy the code

8. Attrgetter function

In the built-in operator library, there is a method to get attributes called attrgetter, which we can use to get the function and execute.

from operator import attrgetter

class People:
    def speak(self, dest) :
        print("Hello, %s" %dest)

p = People()
caller = attrgetter("speak")
caller(p)("Tony") # Hello, Tony
# article 4
caller2 = getattr(p, "speak")
caller2("Tony") # Hello, Tony
Copy the code

9. Methodcaller function

from operator import methodcaller

class People:
    def speak(self, dest) :
        print(f"Hello, {dest}")

caller = methodcaller("speak"."Tony")
p = People()
caller(p)
Copy the code

section

To conclude, this article shares nine ways to use functions: getattr, partial, eval, __dict__, globals, exec, Attrgetter, methodCaller, and __call__.

Please taste them carefully and consider their usage scenarios. Some of these function call methods are used heavily in functional programming or metaprogramming scenarios. I believe you will meet in the future study or work!

Welcome everyone to like, favorites, support!

Pythontip, Happy Coding!

Public number: quark programming