为什么python decorator使函数返回“None”?

2024-04-28 07:06:03 发布

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

有人能帮我理解为什么我的python装饰器不能正常工作吗?你知道吗

创建了一个decorator,在返回count of car\u fuel()函数后打印下面提到的文本。你知道吗

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))

我想得到以下结果:

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

但我得到的是:

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

为什么在“带10张优惠券…”这句话之前我没有收到36张优惠券,为什么它一张也没有?你知道吗


Tags: andoffreeforgetdefcountwrapper
2条回答

因为您的包装函数不返回任何东西-在python中,这意味着隐式的return None。你知道吗

修正:

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

输出:

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

我编辑了装潢师。现在可以正常工作了,谢谢@rdas。你知道吗

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

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

相关问题 更多 >