1

How come the length Current_Stock.open can be greater than 0 if I just created the instance of the class?

def initialize_stock(row):
    Current_Stock=Stock()
    print len(Current_Stock.open)
    do some stuff than return object

Loop that calls initializer

for row in xrange(1,sheet.nrows,25):
        New_Stock= Stock() #create new instance of class
        New_Stock= initialize_stock(row)
        stocks.append(New_Stock) #add instance to stocks array

Stock class

class Stock:
    name=''
    date=[]
    open=[]
    high=[]
    low=[]
    close=[]
    percent_change_price=[]
    percent_change_volume= [] 
BadProgrammer
  • 371
  • 3
  • 17
  • possible duplicate of [How do I avoid having Python class data shared among instances?](http://stackoverflow.com/questions/1680528/how-do-i-avoid-having-python-class-data-shared-among-instances) – user2357112 Feb 25 '15 at 02:03

1 Answers1

1

The reason is, that your attributes are not instance variables, but class attributes.

You declared them on class level -- and in Python this means, that they are class attributes by default.

Only variables that are created inside methods are instance variables and also they must be always used with "self." prefix, e.g.:

 def __init__(self):
     ...
     self.open = []
     ...
Juergen
  • 12,378
  • 7
  • 39
  • 55
  • technically, It doesn't have to be `self` but rather whatever you named the first paramter, which by convention tends to be `self` – FuriousGeorge Feb 25 '15 at 02:10
  • @FuriousGeorge: Off course you are right. But it is good behavior to name it this way, since this is one of the most basic Python conventions. – Juergen Feb 25 '15 at 02:24
  • Does this mean I should make another function called __init__(self)? or should I just set everything to [] at the beginning of my current initialize function? – BadProgrammer Feb 25 '15 at 11:27
  • @BadCode42 the `__init__(self)` is the class inititializer. I really think you should read the python class tutorial (https://docs.python.org/2/tutorial/classes.html) as you seem to not quite have a grasp on how classes work and this is a fundamental idea that you will need to incorporate throughout your code. Better to get a grasp on it now than to propagate problems throughout your code that will be hard to fix later. – FuriousGeorge Feb 25 '15 at 13:10