• Python lists to Class Help
    2 replies, posted
This is my 2nd day programing with python so I'm still new to the language. I have a bit of C++ and I have to say that Python is great. Rely easy to learn, and the syntax isn't a bitch. So my problem. Here's what I'm trying to do. This is the list function and I'm trying to make this into a class so I can call back items in the list through out the program. [CODE] #lists packList = ['sword','helmet','shoes'] print packList #search lists packList.index("helmet") #del from list packList.remove("helmet") print packList [/CODE] This is what I tried to do, but it doesn't seem to work. I'm not sure what to do. [CODE] #BackPackClass class pack1: def packList(): print "this is pack" pList = ['sword','helmet','shoes'] print pList raw_input(" ") start() #Create Pack pack = pack1() #Start main def start(): loop = 1 while loop == 1: print "1)Check Pack" choice = input("Choose your option: ") if choice == 1: pack.packList else: print "Retry" #start main start() [/CODE]
I think you need to go and re-read about classes and functions. In your start function you try to call pack.packList, however you don't add "()" meaning that your just referencing the object. Also you have major problems with your code design. You have your start() function which has infinite loop inside, but inside pack.packList you call start again. This is not needed and will cause a recursion error after a certain amount of time. You should also not be using classes as you currently are. From my point of view it seems like you are going to make individual classes for each type of back, this is a bad way to do things. You should make a class called Pack, that can be passed contents as a constructor arguement: [code] class Pack(): def __init__(self, contents): self.contents = contents def packList(self): print self.contents [/code] Then you should separate the program logic out of the class, so that your code now looks like this: [code] pack = Pack(["helmet", "shorts", "condom"]) while 1: print "1)Check Pack" choice = raw_input("Choose your option: ") #input() is insecure and takes anything typed in as python code if choice == "1": pack.packList() else: print "Retry" [/code] Now obviously this code isn't perfect and there is a lot that needs to be added to make this code nice and easily expandable but this should clean it up enough to set you on the right track.
Thank you. That helps a lot. I found something like a bag class where I can add, del, and refine it. Thanks for your help.
Sorry, you need to Log In to post a reply to this thread.