What does the star operator mean, in a function call?

后端 未结 5 2080
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 06:35

What does the * operator mean in Python, such as in code like zip(*x) or f(**k)?

  1. How is it handled internally in the int
5条回答
  •  后悔当初
    2020-11-21 07:01

    I find this particularly useful for when you want to 'store' a function call.

    For example, suppose I have some unit tests for a function 'add':

    def add(a, b): return a + b
    tests = { (1,4):5, (0, 0):0, (-1, 3):3 }
    for test, result in tests.items():
       print 'test: adding', test, '==', result, '---', add(*test) == result
    

    There is no other way to call add, other than manually doing something like add(test[0], test[1]), which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.

    Another place this is useful is for defining Factory objects (objects that create objects for you). Suppose you have some class Factory, that makes Car objects and returns them. You could make it so that myFactory.make_car('red', 'bmw', '335ix') creates Car('red', 'bmw', '335ix'), then returns it.

    def make_car(*args):
       return Car(*args)
    

    This is also useful when you want to call a superclass' constructor.

提交回复
热议问题