REPOST: Re: odd problem, most likely stupid one too :-)

Tim Roberts timr at probo.com
Sun Dec 30 17:25:27 EST 2001


Dave Harrison <dlharris at mail.usyd.edu.au> wrote:

>Ive written a class named packet, and I have a list on 
>values that I am using to create my packets by passing
>the values in as I instantiate the classes I am creating.
>
>I do the creation in a for loop,
>
>for item in itemlist:
>	PACKET = Packet(item)
>	paclist.append(PACKET)
>
>except that when I try to go back through and see the 
>packets in my paclist they are all exactly the same as
>the final one that I store in the list. As in I do,
>
>for pac in paclist:
>	print pac.getVal()
>
>and I get exactly the same value, despite the fact that
>I know for sure they are different.

This might happen if, for example, you were storing the packets in a class
variable or a global variable instead of an instance variable.  This class,
for example, would behave exactly as you describe:

  class Packet:
      value = Null

      def __init__(self,pkt):
          value = pkt

      def getVal(self):
          return self.value

The solution is to skip the class global:

  class Packet:
      def __init__(self,pkt):
          self.value = pkt

      def getVal(self):
          return self.value
--
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.

========= WAS CANCELLED BY =======:
Path: news.sol.net!spool1-nwblwi.newsops.execpc.com!newsfeeds.sol.net!priapus.visi.com!zeus.visi.com!news-out.visi.com!hermes.visi.com!newspeer.monmouth.com!news-xfer.nuri.net!feeder.kornet.net!news1.kornet.net!ua4canc3ll3r
From: Tim Roberts <timr at probo.com>
Newsgroups: comp.lang.python
Subject: cmsg cancel <am4v2u0pcfsu8511i5213ii7tq02gmqosc at 4ax.com>
Control: cancel <am4v2u0pcfsu8511i5213ii7tq02gmqosc at 4ax.com>
Date: Mon, 31 Dec 2001 02:15:36 GMT
Organization: A poorly-installed InterNetNews site
Lines: 2
Message-ID: <cancel.am4v2u0pcfsu8511i5213ii7tq02gmqosc at 4ax.com>
NNTP-Posting-Host: 211.57.49.2
X-Trace: news2.kornet.net 1009774037 27193 211.57.49.2 (31 Dec 2001 04:47:17 GMT)
X-Complaints-To: usenet at news2.kornet.net
NNTP-Posting-Date: Mon, 31 Dec 2001 04:47:17 +0000 (UTC)
X-No-Archive: yes
X-Unac4ncel: yes
X-Commentary: I love NewsAgent 1.10 and the Sandblaster Cancel Engine Build 74 (19 March 1999)

This message was cancelled from within Mozilla.



More information about the Python-list mailing list