1

(1) 我在第一行定义了一个函数。
关于 (2) 我在第 5 行定义了相同的函数。

哪个更快?正在定义一个“更接近”我需要的函数对于大型程序的复杂性不切实际(但它是否使它更快),或者定义一个函数“远离”我需要它在运行时使更大的程序变慢(但也更实用)。

我正在使用python。当然,这里的差异可能以纳秒为单位,但这只是一个例子。

1-

def t(n1,n2):
    v=n1-n2
    return abs(v)
a = int(input('how old are you? \n'))
b = int(input('how old is your best friend? \n'))

c=t(a,b)

if a==b:
    print ('you are both the same age')

else:
    print('you are not the same age\nthe difference of years is %s year(s)' % c)

input()

2-

a = int(input('how old are you? \n'))
b = int(input('how old is your best friend? \n'))

def t(n1,n2):
    v=n1-n2
    return abs(v)

c=t(a,b)

if a==b:
    print ('you are both the same age')

else:
    print('you are not the same age\nthe difference of years is %s year(s)' % c)

input()
4

2 回答 2

2

Both are the same. As long as you don't call a function (or use a variable etc.) before defining it, it doesn't matter where you put it. All your code is optimized by the Python interpreter anyway, and it couldn't care less how "far" away from the function call the function is defined.

于 2013-09-01T03:13:51.193 回答
0

该函数在您调用它之前被解析。所以你在哪里定义它并不重要。

于 2013-09-01T03:29:47.800 回答