简体   繁体   中英

What's happening inside this Python decorator?

So my question pertains specifically to the decorator at the top of the example below. I don't understand the 3rd line of the lowercasedecorator function. I'm confused why it's returning a list, if it's in those square brackets, it means it's a list right? Also, I don't completely understand the end of that line 'func(*args)', does that just mean arbitrary arguments of 'func' (which in this case would be displayPeople) ?

def lowercasedecorator(func):
    def wrapper(*args):
        return [i.lower() for i in func(*args)]
    return wrapper

class People():
    totalpeople = 0
    def __init__(self, name, age, phone):
        self.name=name
        self.age=age
        self.phone=phone
        People.totalpeople += 1

    @lowercasedecorator
    def displayPeople(self):
        return self.name, self.age, self.phone

ben = People("bEn", "20", "5034950293")

print ben.displayPeople()
def wrapper(*args):
    return [i.lower() for i in func(*args)]

The * syntax in the call to func (that is, displayPeople ) passes the same positional arguments that wrapper received.

wrapper does indeed return a list.

Because of how decorators work, the function wrapper created with func = displayPeople is the decorated version of displayPeople .

So, the effect of the decorator is that the decorated version of displayPeople calls the undecorated version, lower-cases the returned values, and returns them as a list.

Line #3 is a list comprehension . The can be used instead of a for loop.

func(*args) is indeed unpacking the tuple that is being passed in on line 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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