scope, modyfing outside object from inside the method

Marcin Stępnicki mstepnicki at gmail.com
Mon Sep 24 02:43:08 EDT 2007


Hello.

I thought I understand this, but apparently I don't :(. I'm missing
something very basic and fundamental here, so redirecting me to the
related documentation is welcomed as well as providing working code :).

Trivial example which works as expected:

>>> x = {'a':123, 'b': 456}
>>> y = x 
>>> x['a']=890
>>> y
{'a': 890, 'b': 456}

Now, let's try something more sophisticated (it's not real world example,
I've made up the problem which I think illustrates my issue). Let's say
I've got such a structure:

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

I'd like to have each row and column in separate object of self-made
classes.:

class mycolumn():
  def __init__(self, resultset, row, col):
	self.value = resultset[row][col]
  def __str__(self):
	return 'Column value: %s' % self.value

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

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

mystruct = []

for row in results:
	mystruct.append ( myrow() )
	for col in row:
 	       	mystruct [len(mystruct)-1].container[col] = \
			 mycolumn(results, results.index(row), col)

print mystruct[0].container['b'] # 12
results[0]['b'] = 50             # 
print mystruct[0].container['b'] # also 12 :/

In other words, I'd like to "map" the results to myrow and mycolumn
objects, and have these new objects' values changed when I change "results".

I hope I explained it well enough :). Thank you for your time.

-- 
| 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