Steven D'Aprano a écrit :
On Wed, 24 Mar 2010 21:14:23 -0700, Tim Roberts wrote:
Jimbo <nill...@yahoo.com> wrote:
class stock:
code = ""
purchasePrice = 0
purchaseQuantity = 0
price = [] # list of recent prices
recentBid = [] # list of recent bids for stock
recentOffer = [] # list of recent offers for stock
stockVol = [] # list of stock quantity available on market
Using lists as class variables is a very good way to create very
surprising bugs. Consider the following:
[snip]
Don't you think that the class attributes are *supposed* to be shared by
all instances? In that case the behaviour you show is not a bug at all.
Python's class attributes are indeed supposed to be shared - that's even
the whole point of having class attributes.
But this feature has proven to be confusing for newcomers that more
often than not have previous exposure to OOPLs where you do "declare"
your class "schema" at the class level (where Python defines class
attributes).
Now reread the OP's code, and you'll find out he's indeed yet another
victim of this gotcha:
"""
for row in cur.fetchall():
newStock = stock()
newStock.code = row[0]
newStock.purchasePrice = row[1]
newStock.purchaseQuantity = row[2]
cur.execute(stockQuery,[newStock.code])
for rw in cur.fetchall():
newStock.price.append(rw[0])
newStock.recentOffer.append(rw[1])
newStock.recentBid.append(rw[2])
newStock.stockVol.append(rw[3])
stockList.append(newStock)
"""
--
http://mail.python.org/mailman/listinfo/python-list