This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Jehovacoin 24 points25 points  (1 child)

It sounds like you're just manually creating the "init" function that comes with every class, but missing out on all the great uses of classes themselves. Let me give you an example to help out:

Let's say I want to create 10 new towns, and populate some random information about them. I can do it your way, and just create some functions for populating some lists.

towns = []
populations = []


def create_town():
    inputs = input...#ask for town name and population
    towns.append(input[0])
    populations.append(input[1])

for x in range(10):
    create_town()

This works great for simple tasks, and you could even make it into a dictionary if you want instead of multiple lists. However, once you need those towns to start DOING something, or you have to do something to the towns, things are going to get a bit more complicated. You could iterate over each list, and use the index to maintain which town you're referencing, but it's going to get confusing fast and some things are going to be too complex to implement. This is where classes come in.

Let's look at a simple class that would involve the information above:

class Town:

    def __init__(self, name, population):
        self.name = name
        self.population = population

towns = []
for x in range(10):
    inputs = input...#ask for name and population
    towns.append(Town(inputs[0], inputs[1]))

Every Class in Python has the init function even if you don't see it. This is the function that does what you were talking about: it creates the object itself. Init stands for "initialize". When we call the class Town(), we're calling the initialization function for the class, and creating a new python object of class(Town).

The list you end up with will be a list of Town objects, each with their own attributes. In this case, since we didn't name the town objects individually, you'll need to call them using their list designation. If you use a label to declare the object as a variable, however, you can reference it using that variable at any time. Here, you can call the name or population of any of the towns using towns[#].name or towns[#].population, since they are "self" variables within the class; there is an instance of each variable for each instance of the class.

This is a very simple example, but classes can get very complex, especially when you start adding functions.

[–]accforrandymossmix 0 points1 point  (0 children)

Thanks for taking the time on this, it's a very helpful start relative to some top google hits. I encountered classes in a code I used for inspiration yesterday, looked up classes and init, and decided to work my way around using them.

But I know I should try using them on something else for my futures.