简体   繁体   English

为什么 python 装饰器使 function 返回“无”?

[英]why does python decorator make a function to return “None”?

Guys can someone help me to understand why doesn't my python decorator work properly?有人可以帮我理解为什么我的 python 装饰器不能正常工作吗?

created a decorator that would print the below mentioned text after returning the count of car_fuel() function.创建了一个装饰器,它将在返回 car_fuel() function 的计数后打印下面提到的文本。

def decor(func):
    def wrapper(a):
        func(a)
        print('Bring 10 coupons and get a gallon of fuel for free')
    return wrapper



@decor
def car_fuel(a):
    b={'petrol':3.6,'diesel':3} #types of fuel and prices
    count = 0
    for i in a.keys():
        if i in b.keys():
            count+= a[i]*b[i]
    return count


abc={'petrol':10} # the fuel that i wanna buy and gallons
print(car_fuel(abc))

I want to have the following result:我想得到以下结果:

36 Bring 10 coupons and get a gallon of fuel for free 36 携带10张优惠券,免费获得一加仑燃油

but what I get is:但我得到的是:

Bring 10 coupons and get a gallon of fuel for free None带 10 张优惠券可免费获得一加仑燃油 无

Why don't I receive 36 before the "Bring 10 coupons...." sentence and why does it return None?为什么在“Bring 10 coupons....”语句之前我没有收到 36,为什么它返回 None?

Because your wrapped function doesn't return anything - in python that means an implicit return None .因为您包装的 function 不返回任何内容 - 在 python 中,这意味着隐式return None

Fix:使固定:

def decor(func):
    def wraper(a):
        ret = func(a) # save return value
        print('Bring 10 coupons and get a gallon of fuel for free')
        return ret    # return it
    return wraper

Output: Output:

Bring 10 coupons and get a gallon of fuel for free
36.0

I edited the decorator.我编辑了装饰器。 now it works properly thanks @rdas.现在它可以正常工作了,感谢@rdas。

`def decor(func):
        def wraper(a):
            r=func(a)

            return str(r)+'\n'+'bring 10 coupons and get 10l free fuel'
        return wraper`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM