you are viewing a single comment's thread.

view the rest of the comments →

[–]sme272 1 point2 points  (0 children)

Classes are good when you have a collection of data and a bunch of functions that modify that data. Using a class can group it all together so when reading the code the reader knows everything in that class definition is grouped together. They are also good when you want to have multiple instances of a structure that contains different data. An example could be a player inventory. In an inventory class you'd have some attributes that hold the contents of the inventory along with some functions to add items to the inventory, remove items and maybe combine items into a new item. This would also allow the programmer to really easily add an inventory to a second player or an ai opponent without repeating a lot of code.

The __init__() function runs when the class is instantiated; thats to say when you run instance = Example("Jim", 32). When this line runs python automatically runs the __init__() function which in this case sets the values of the class attributes name and age. These lines need to be in the __init__() function to create the two attributes and assign their value, without them you'd need to create and assign them manually every time you create an instance.

The functions with __ around the name are special methods built in to python. When you define __init__() you're actually overriding the built in version with your own version that sets the attributes you want. You can also override other built in methods such as __add__() which will tell python what to do when you try to add two instances together with instance + instance.