Qiang Zhang
Qiang Zhang

Reputation: 952

A bug about decorator in Python

The code is given as following:

import time
import sys

def LogClassFuncInfos(func):
    def wrapper(*s, **gs):
        methodName = format(func.__name__)
        print(methodName)
        func(*s, **gs)
    return wrapper

class NameModel():

    def __init__(self):
        self.name = 'test'

    @LogClassFuncInfos
    def getName(self):
        return self.name

a = NameModel()
print(a.getName())

The code is expected to print 'test', but the code prints None.

If the @LogClassFuncInfos before def getName(self) is removed, the 'test' can be normally printed.

Upvotes: 0

Views: 62

Answers (1)

timgeb
timgeb

Reputation: 78650

You forgot to return the result of func(*s, **gs) in wrapper.

Upvotes: 4

Related Questions