![]() |
Classes question
I'm having a bit of trouble figuring out classes. Here's a rough example of what I'm trying to do:
class Item_Class: def __int__(self): self.Name self.Description self.Price List[] List.append(Item_Class) List[0].Name = "Something" List[0].Description = "Something" List[0].Price = "Something" That works fine. But if I append the class to the list a second time, and assign some values to it, the previous instance of the class is changed to those values also. What am I doing wrong? Isn't the idea of classes to be able to make different instances of it? thanks |
You need to change "List.append(Item_Class)" to "List.append(Item_Class())". The () initiates a new object for that class. You were appending to the list the direct reference to the class.
The following is a working example... Note that the class's contents are completely blank. This is because you're declaring and initiating the variables externally. There is no need to put anything inside. :
class Item_Class:However, if you want to write it in a way that provides a better understanding of how classes work, then consider the following... :
class Item_Class:Furthermore expanding on the program, we can get the same output like so... :
class Item_Class:If anything I'm doing confuses you, don't hesitate to ask any questions. I also strongly suggest that you use the search to look through the Python forum for more examples using classes. I believe there's some excellent information provided by Arevos lying around. I also urge you to use [code][/code] tags next time you post code. |
Ahh, that makes sense. Thank you very much for simple and clear example.
On a related note were can I find out more about the different ways classes are used in programming? BTW sorry about not puting the code in tags, I was going to but forgot because I was doing a couple things at the same time(maybe I should cut down on the Dr.pepper). thanks again |
The way classes are used in programming are for you to discover and apply yourself as a programmer. The applications of Object-Oriented programming are very vast, and can be applied basically anywhere. But the more you use it as a programmer, the more you'll see where it should and should not be applied.
Otherwise, I hope wherever you're learning classes from explains the general applications of classes, and where and where not to use them. |
| All times are GMT -5. The time now is 1:26 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC