scope, modyfing outside object from inside the method

Marcin Stępnicki mstepnicki at gmail.com
Wed Sep 26 15:39:22 CEST 2007


Dnia Mon, 24 Sep 2007 10:41:22 -0300, Ricardo Aráoz napisał(a):

> Would this work for you?

Thank you both for help. Well - yes and no :). It's getting more
interesting:

First, your code:

class myrow():
  def __init__(self, idict = {}):
        self.container = idict
  def __str__ (self):
        return self.container.__str__()

results = [
        {'a': 12, 'b' :30 },
        {'a': 13, 'b' :40 }
]

mystruct = []

for row in results:
    mystruct.append(myrow(row))

results[1]['b'] = 444

print results  # [{'a': 12, 'b': 30}, {'a': 13, 'b': 444}]

print mystruct # does not work ok , you should probably define
               # mystruct's __str__ method properly

# But, save for the __str__ thingy, the rest is ok.

for row in mystruct:
    print row

# {'a': 12, 'b': 30}
# {'a': 13, 'b': 444}

And now let's try to swap results with something else:

print id(results)

# new resultset 
results = [
        {'a': 112, 'b' : 130 },
        {'a': 113, 'b' : 140 }
]

print id(results)
for row in mystruct:
    print row

# {'a': 12, 'b': 30}
# {'a': 13, 'b': 444}

At first glance (before adding id()) it's a little bit weird. The original
object was supposedly "overwritten", but as one can see it has different
id then the new one. mystruct still holds references to old object,
though. I can handle it and just change original object, but I'm curious
if there's a way to "swap" them "on-the-fly".

Thanks one again.

-- 
| And Do What You Will be the challenge | http://apcoln.linuxpl.org
|    So be it in love that harms none   | http://biznes.linux.pl
|   For this is the only commandment.   | http://www.juanperon.info
`---*  JID: Aragorn_Vime at jabber.org *---' http://www.naszedzieci.org



More information about the Python-list mailing list