0

Hopefully I asked this question correctly. I have the code example:

class myc:
    a = ['a', 'b']

    def f1(self):
        b = myc.a
        b.extend(['c', 'd'])
        return b

    def f2(self):
        b = myc.a
        b.extend(['f','g'])
        return b


cvar = myc()

print cvar.f1()
print cvar.f2()
print cvar.f1()

I get the output:

['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'f', 'g']
['a', 'b', 'c', 'd', 'f', 'g', 'c', 'd']

What I want is for "a" to be static.

My understanding is that because of "binding", when I do "b = myc.a" and I then do "b.extend...", I am actually affecting myc.a.

What I want is to make a copy of myc.a and store it in b so that my operations on b, don't affect myc.a.

I am obviously missing some basic Python concept here beyond binding.

The output I want is:

['a', 'b', 'c', 'd']
['a', 'b', 'f', 'g']
['a', 'b', 'c', 'd']
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
GregH
  • 12,278
  • 23
  • 73
  • 109
  • 1
    I think you'll find this helpful: [Facts and myths about Python names and values](http://nedbatchelder.com/text/names.html), by SO veteran Ned Batchelder. – PM 2Ring Aug 29 '15 at 05:54
  • Here's a video version of @PM-2Ring's link: [link](https://youtu.be/_AEJHKGk9ns) – Nick Fegley Aug 29 '15 at 06:32
  • I guess this came down less to a variable/binding problem and more of an issue related to lists. Looks like you clone it by either: v = x[:] or more preferably v = list(x) – GregH Aug 29 '15 at 15:04

0 Answers0