我正在尝试根据调用它的次数逐步更新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(),然后一旦调用函数2(),就会创建function3(),依此类推。有没有一种直截了当的方式可以解决这个问题?
答案 0 :(得分:1)
你不应该声明这样的多个功能,有更好的方法来实现你想要的。
使用生成器非常适合您的特定示例。
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
答案 1 :(得分:0)
这可以是解决此问题的理想方法,而不是为每个增量创建多个函数。使用类并将计数器存储为变量并调用相应的方法来递增和get_count
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