首先要找到两个数字的“lcm”,我做了一个函数
lcm(a, b)
. 后来我也想到找“HCF”所以我做了一个装饰工
decor
定义了一个函数
hcf(a, b)
在里面。然后我只输入函数名就返回了这个函数,我没有在它上面加括号,但它仍然在工作。即使我没有使用括号,我也不明白为什么这个函数能工作。
def decor(lcm_arg): # just to practice decorators
def hcf(a, b):
if a > b:
a, b = b, a
while True:
if b % a == 0:
print("hcf is", a)
break
else:
a, b = b % a, a
return lcm_arg(a, b)
return hcf # how hcf function is working without using brackets
@decor
def lcm(a, b):
if a > b:
a, b = b, a
for x in range(b, a*b+1, b):
if x % a == 0:
print("lcm is", x)
break
lcm(2, 4)
输出:
hcf is 2
lcm is 4