简体   繁体   中英

Assigning function to variable in Python

I have a function that returns a tuple.

    def x():
        ...
        return (a, b, c, d)
    var = x()
    print (var[1], var[2])

In this case, is the function called each time I use one of the tuple objects? My hopes are that the function is only called once, at the time of the assignment to variable.

Sorry for the newbie question.

No, your function is only called once. Likewise, your tuple is only created once, that is at the call var = x() .

var[2] simply accesses the already existing tuple`s entry at a particular position, here third position (counting starts at 0).

The function is executed only once, when you call it, specifically in this line:

var = x()

In your next line, you are just working with the var variable that function output was assigned to.

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