Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #25922 > unrolled thread
| Started by | "Russell E. Owen" <rowen@uw.edu> |
|---|---|
| First post | 2012-07-23 14:00 -0700 |
| Last post | 2012-07-23 14:00 -0700 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: What's wrong with this code? "Russell E. Owen" <rowen@uw.edu> - 2012-07-23 14:00 -0700
| From | "Russell E. Owen" <rowen@uw.edu> |
|---|---|
| Date | 2012-07-23 14:00 -0700 |
| Subject | Re: What's wrong with this code? |
| Message-ID | <mailman.2499.1343077256.4697.python-list@python.org> |
In article
<CAPTjJmqrhztsUkRSYb56=TX=hDomVo8mePcSY0yTjAUpTcmJtA@mail.gmail.com>,
Chris Angelico <rosuav@gmail.com> wrote:
> On Tue, Jul 24, 2012 at 12:50 AM, Stone Li <viewfromoffice@gmail.com> wrote:
> >
> > I'm totally confused by this code:
> >
> > Code:
>
> Boiling it down to just the bit that matters:
>
> c = None
> d = None
> x = [c,d]
> e,f = x
> c = 1
> d = 2
> print e,f
>
> When you assign "e,f = x", you're taking the iterable x and unpacking
> its contents. There's no magical "referenceness" that makes e bind to
> the same thing as c; all that happens is that the objects in x gain
> additional references. When you rebind c and d later, that doesn't
> change x, nor e/f.
>
> What you've done is just this:
>
> x = [None, None]
> e,f = x
> c = 1
> d = 2
> print e,f
>
> It's clear from this version that changing c and d shouldn't have any
> effect on e and f. In Python, any time you use a named variable in an
> expression, you can substitute the object that that name is
> referencing - it's exactly the same. (That's one of the things I love
> about Python. No silly rules about what you can do with a function
> return value - if you have a function that returns a list, you can
> directly subscript or slice it. Yay!)
Good explanation.
Perhaps what the original poster needs is a container of some kind, e.g.
a class with the value as an instance variable. Then you can pass around
references to the container and read or modify the value(s) stored in it
when you need them.
Here is a simple example:
class Container(object):
def __init__(self, value):
self.value = value
c = Container(5)
d = Container(6)
x = [c, d]
e, f = x
c.value = None
d.value = "hello"
print e.value, f.value
None "hello"
-- Russell
Back to top | Article view | comp.lang.python
csiph-web