如何判断何时第一次调用某个方法 [英] How to tell when a method is called for first time of many

查看:71
本文介绍了如何判断何时第一次调用某个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么时候第一次被调用.当我打印到定界文件时,我主要需要它,如果是第一次迭代,我想在实际信息之前打印标题.这是我通常要做的:

I would like to be able to tell when a method has been called for the first time. I primarily need this for when I am printing out to a delimited file, and if it is the first iteration, I would like to print a header before the actual information. This is what I normally do:

def writeFile(number, count):
    if count == 1:
        print('number')
        print(str(count))
    else:
        print(str(count))


count = 1
for i in range(10):
    writeFile(i, count)
    count += 1

这提供了以下输出:

number
1
2
3
4
5
6
7
8
9
10

尽管这达到了我追求的目标,但我对是否有更好/更有效的方法感到好奇.是否有某种方法可以检测是否已首次调用某个方法,而不必将附加参数传递给该方法?

Though this achieves the goal I am after, I am curious as to if there is a better/more efficient way of doing this. Is there some way to detect if a method has been called for the first time without having to pass an additional argument to it?

谢谢

推荐答案

有多种方法可以做到这一点.这是三个.

There are multiple ways to do this. Here are three.

第一:

firstRun=True
def writeFile(number):
    global firstRun
    if firstRun:
        print('number')
        firstRun=False
    print(str(number))

for i in range(10):
    writeFile(i)

第二:

def writeFile(number):
    print(str(number))

for i in range(10):
    if not i:
        print('number')
    writeFile(i)

第三:

for i in range(10):
    print(('' if i else 'number\n')+str(i))

我假设这只是一个测试问题,旨在表明函数调用初始化或重置数据的情况.我更喜欢从调用函数中隐藏信息的代码(例如1).我是Python的新手,所以我可能使用了不良做法.

I'm assuming this is just a test problem meant to indicate cases where function calls initialize or reset data. I prefer ones that hide the information from the calling function (such as 1). I am new to Python, so I may be using bad practices.

这篇关于如何判断何时第一次调用某个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆