osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Tutor] beginning to code


bartc <bc at freeuk.com>:

> On 22/09/2017 10:23, Marko Rauhamaa wrote:
>> However, Python doesn't need any language changes to implement memory
>> slots. A memory slot could be defined as any object that implements
>> "get()" and "set(value)" methods:
>
> I didn't understand your examples.
>
> Can Python be used to write, say, a swap() function that works with any
> argument types (not just classes or lists)? Example:
>
>     def swap(&a,&b):        # made up syntax
>         a, b = b, a
>
>     x=10
>     y="Z"
>     swap(x,y)
>     print (x,y)             # "Z" and "10"

Yes, following my recipe:

   def swap(ref_a, ref_b):
       a, b = ref_a.get(), ref_b.get()
       ref_a.set(b)
       ref_b.set(a)

   x = 10
   y = "Z"
   swap(slot_ref(locals(), "x"), slot_ref(locals(), "y"))
   print(x, y)             # "Z" and 10


Marko