Python map function, passing by reference/value?

前端 未结 3 1955
天命终不由人
天命终不由人 2021-01-12 11:23

I have a question about the map function in Python.

From what I understand, the function does not mutate the list it\'s operating on, but rather create

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-12 11:52

    You misunderstand how references work in Python. Here, all names are references, there are no "values". Names are bound to objects. But = doesn't modify the object that's pointed to by the name — it rebinds the name to a different object:

    x = 42
    y = x
    # now:
    # 'is' is a identity operator — it checks whether two names point to the
    # exact same object
    print x is y # => True
    print x, y   # 42 42
    y = 69
    # now y has been rebound, but that does not change the '42' object, nor rebinds x
    print x is y # => False
    print x, y   # 42 69
    

    To modify the object itself, it needs to be mutable — i.e. expose members that mutate it or have a modifiable dict. The same thing as above happens when you rebind p — it doesn't touch points at all, it simply modifies the meaning of local p name.

    If you want to simulate C++-like references, you need to encapsulate the object into a mutable container, e.g. a list.

    reflect([points], 'X')
    
    # inside reflect:
    p[0] = ...
    

    But you shouldn't, at least in this case — you should just return the new object instead.

    points = reflect(points, 'X')
    
    # inside reflect, instead of p = ...
    return map(func, p)
    

    Well, now that I think about it, you can also do

    p[:] = map(func, p)
    

    But again, returning new object is usually better.

提交回复
热议问题