I'm trying to get a grasp on how lists behave. I've included two VERY simple .py programs. I'm trying to get comfortable using oop (I can do blunt code...but oop trips me up...)
my question is can anyone explain how is python treating the lists? In one program I instantiate the list in the class...in the second program I do not. The only thing I can think of is I need to instantiate in class0.py __init__ func when the list is such that it will take in user's input? idk if this explanation is correct
I've better elaborated my question in the code comment...please help. Thx && HAPPY HOLIDAYS!!!!!
#class0.py class Sur(): def __init__(self): self.things = [] #pls note list is instantiated...but in class1.py I don't use it? def add_info(self,new_ish): self.things.append(new_ish) print('added:',new_ish) return new_ish def print_all(self): for j in self.things: print(j)
#run0.py from class0 import Sur Surv=Sur() listt=[] #instantiated here as well since list exists in __init__ for i in range(1,2): incoming = str(input('> ')) if incoming == 'q' or incoming =='': break else: Surv.add_info(incoming) Surv.print_all()
#class1.py import random class Die(): def __init__(self,sides=6): self.sides = sides #notice there is no instantiation of list in this file #QUESTION IS WHY IS THIS???? def roll(self,turn): self.turn = random.randint(1,self.sides) return self.turn
#run1.py from class1 import Die foo =Die() results = []#why isn't there a list in class1 ---IDU this!!! for i in range(1,2): drop = foo.roll(i) results.append(drop) print(str(i)+']'+str(drop))