[Tutor] beginning to code
On 22/09/2017 12:47, Chris Angelico wrote:
> On Fri, Sep 22, 2017 at 9:24 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
>> Yes, following my recipe:
>> def swap(ref_a, ref_b):
>> a, b = ref_a.get(), ref_b.get()
>> x = 10
>> y = "Z"
>> swap(slot_ref(locals(), "x"), slot_ref(locals(), "y"))
>> print(x, y) # "Z" and 10
> Sure, let me just put that into a function. CPython 3.7, although I'm
> pretty sure most CPython versions will do the same, as will several of
> the other Pythons.
> (Side point: Your slot_ref function is rather bizarre. It's a closure
> AND a class, just in case one of them isn't sufficient. The following
> code is copied and pasted from two of your posts and is unchanged
> other than making try_swapping into a function.)
>>>> def slot_ref(dict_or_array, key_or_index):
> ... class SlotRef:
> ... def get(self): return dict_or_array[key_or_index]
> ... def set(self, value): dict_or_array[key_or_index] = value
> ... return SlotRef()
>>>> def swap(ref_a, ref_b):
> ... a, b = ref_a.get(), ref_b.get()
> ... ref_a.set(b)
> ... ref_b.set(a)
>>>> def try_swapping():
> ... x = 10
> ... y = "Z"
> ... swap(slot_ref(locals(), "x"), slot_ref(locals(), "y"))
> ... print("x, y =", x, y)
> x, y = 10 Z
> Strange... doesn't seem to work. Are you saying that Python is
> pass-by-reference outside of a function and pass-by-value inside?
> Because that'd be just insane.
> Or maybe what you have here isn't a real reference at all.
It also looks too complicated to be really useful. And I'm not sure it
would work (when it does work), with more complex terms. For simple given:
A = [10,20,30]
B = ["X","Y","Z"]
and wanting to swap A and B. Although these being list elements,
they /could/ be exchanged via a function:
Just not using a general-purpose swap function.