简体   繁体   中英

How to understand '*' in below python code

When I reading code MySQLdb, in times.py, i can not understand one line code:

return date(*localtime(ticks)[:3])

Any one can tell me what's use of '*', thanks a lot.

It's known as the splat operator which turns a sequence into positional arguments to be used by that given function. There is also a double splat operator in case you didn't know which converts a dict to named arguments which are then passed to the function. Also read this for more relevant discussion.

As an example:

def printIt(*args, **kwargs):
  print 'Splat Contents=%s' % str(args)
  print 'Double Splat Contents=%s' % str(kwargs)

lst = [1, 2, 3]
dct = { 'name': 'sanjay', 'age': 666 }
printIt(*lst, **dct) # usage

So basically to conclude, splat when used in function application means "take this sequence, unpack it and pass it as positional arguments". splat when used in function definition means "this functions takes a variable number of positional arguments". Similar reasoning can be applied to the double splat operator. This is the reason the most generic function definition looks something like def funcName(*args, **kwargs) (as already posted in my example which can handle any sort of arguments).

I will try to explain it by example. The following code

params = [1, 2, 3]
func(*params)

Is equivalent to this:

func(1, 2, 3)

So this basically allows you to call a function with parameters coming from a list. In you particular example there's a function call (which returns a list) and a list slicing added, but you should have figured that out.

它将的前三个元素解压缩到localtime(ticks) ,并将它们用作date函数的参数。

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