解释probsond.calls如何等于零

2024-09-30 16:34:14 发布

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

def MainCount(f):
    def progFirst(*args,**kwargs):
        progFirst.calls+=1
        return f(*args,**kwargs)
    progFirst.calls=0
    return progFirst
@MainCount
def progSecond(i):
    return i+1

@MainCount
def Count(i=0,j=1):
    return i*j+1
print(progSecond.calls)
for n in range(5):
    progSecond(n)
Count(j=0,i=1)
print(Count.calls)

输出:0 一,

根据我的理解,MainCount(probsond),但我不明白probsond.calls如何等于零,同样在Count.calls中也是如此


Tags: inforreturndefcountargsrangekwargs
1条回答
网友
1楼 · 发布于 2024-09-30 16:34:14

正如您在MainCount函数probFirst.Calls中所看到的,当MainCount(probSecond)现在时,probSecond.Calls也是MainCount函数的属性

# A Python example to demonstrate that 
# decorators can be useful attach data 

# A decorator function to attach 
# data to func 
def attach_data(func): 
    func.data = 3
    return func 

@attach_data
def add (x, y): 
    return x + y 

# Driver code 

# This call is equivalent to attach_data() 
# with add() as parameter
print(add(2, 3)) 

print(add.data) 

相关问题 更多 >