例如,我有功能Ball()。在该函数中,我导入了一个带有Ball名称的列表,我在其中随机选择一个并返回该名称。所以我想知道如何计算该功能的访问次数。
我尝试过:
def Ball():
counter = 0
Ball_name = Ball.man
Ball_name = random.choice(Ball_name)
counter = counter+1
return Ball_name
counter_1 = Ball(counter)
print(counter_1)
但是它没有用。谢谢您的帮助,我真的。但是我不希望有任何答案说我必须从入门或其他方面学习Python。我需要真正的帮助,因为我因此而感到非常压力。我不能使用全局变量谢谢
您可以给函数一个属性,例如count
,并在每次调用该函数时将其递增。
def Ball():
if not hasattr(Ball, 'count'):
Ball.count = 0
Ball.count += 1
Ball()
print(Ball.count) # will print 1
Ball()
print(Ball.count) # will print 2
如果您想进一步了解PEP 232 -- Function Attributes,可以查看一下。
如果您只有一个要计数的函数,那么侵入函数属性就可以解决问题。
有关更一般的解决方案,可以使用decorators:
def count(f):
def f_with_counter(*args, **kwargs):
if not hasattr(f_with_counter, 'count'):
f_with_counter.count = 0
f_with_counter.count += 1
return f_with_counter
@count
def Ball():
pass
#whatever it is that Ball does
Ball()
print(Ball.count) # should print 1 just as in the example above
Ball()
print(Ball.count) # should print 2 now.