我可以在Python中动态更新函数名吗?

2024-04-20 09:21:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试根据Python函数被调用的次数递增地更新它的名称。你知道吗

原始函数的示例如下所示:

    def function(): 
       function.counter += 1
       return print('call 0')

function.counter = 0 

下面是我希望在第二次调用上述函数时生成的函数:

def function1(): 
    function.counter1 += 1
    return print ('call 1') 

依此类推,每次调用前一个函数,都会创建一个新函数,将前一个函数的名称加1。一旦调用了function1(),就会创建function2(),然后一旦调用了function2(),就会创建function3(),依此类推。我有没有直截了当的办法?你知道吗


Tags: 函数名称示例returndefcounterfunctioncall
2条回答

你不应该像那样声明多个函数,有更好的方法来实现你想要的。你知道吗

发电机

使用生成器非常适合您的特定示例。你知道吗

def count(start=0):
    while True:
        yield start
        start += 1

g1 = count()
next(g1) # 0
next(g1) # 1

g10 = count(10)
next(g10) # 10

itertools模块

前面的示例已经由itertools.count实现。你知道吗

from itertools import count

g1 = count()
next(g1) # 0
next(g1) # 1

g10 = count(10)
next(g10) # 10

关闭

如果希望函数具有某种状态,请使用闭包而不是函数属性。你知道吗

def count(start=0):
    _state = {'count': start - 1}

    def inner():
        _state['count'] += 1
        return _state['count']

    return inner

f1 = count()
f1() # 0
f1() # 1

这是解决这个问题的理想方法,而不是为每个函数创建多个函数增量使用一个类,将计数器存储为变量,并调用相应的方法来递增并获取\u计数

class CouterExample(object):
    """Sample DocString:

    Attributes:
        counter: A integer tracking the current counter.
    """

    def __init__(self, counter=0):
        """Return a CounterExample object with counter."""
        self.counter = counter

    def increment(self, amount):
        """Sets the counter after increment."""
        if amount > 1:
            self.counter += amount

    def get_counter(self):
        """Return the counter value."""
        return self.counter

相关问题 更多 >