Advice Criticism on Python App

Tim Roberts timr at probo.com
Thu Mar 25 05:14:23 CET 2010


Jimbo <nilly16 at 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:

  C:\Dev>type x.py

  class test:
      check = []
      def __init__(self):
          self.check.append(1)

  x = test()
  y = test()
  z = test()
  print x.check
  print y.check
  print z.check

  C:\Dev>x.py
  [1, 1, 1]
  [1, 1, 1]
  [1, 1, 1]

  C:\Dev>

>    def __init__(self):
>        """ Default Constructor """
>        self.code             = ""
>        self.purchasePrice    = 0
>        self.purchaseQuantity = 0
>
>    def constructor(self, stockCode, purPrice, purQuant):
>        """ Constructor """
>        self.code             = stockCode
>        self.purchasePrice    = purPrice
>        self.purchaseQuantity = purQuant

The "constructor" concept here is not very Pythonic.  Why not replace those
both with:

    def __init__(self, stockCode="", purPrice=0, purQuant=0):
        self.code             = stockCode
        self.purchasePrice    = purPrice
        self.purchaseQuantity = purQuant
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list