Python Classes

Python Classes

·

3 min read

Why classes?

example

Let's say we're trying to organize data of the people living in a village. Without Classes, it would look like this:

p1 = {'name': 'Josh', 'age': 18, 'sex': 'male', 'hobby': 'reading'}
p2 = {'name': 'Eric', 'age': 32, 'sex': 'male', 'hobby': 'playing guitar'}
p3 = {'name': 'Anna', 'age': 10, 'sex': 'female', 'hobby': 'running'}
p4 = {'name': 'Rick', 'age': 70, 'sex': 'male', 'hobby': 'crafting'}

This might look quite organized, but imagine repeating this process 1000 times, for each person in the village. It becomes even worse if you have like 100 variables for each person. Even when extracting data from a person, it would be confusing and tiring.

Here's how to do it with CLASSES:

class Villiger(): 
    def __init__(self, name, age, sex, hobby)
        self._name = name
        self._age = age
        self._sex = sex
        self._hobby = hobby

p1 = Villiger(Josh, 18, male, reading)
p2 = Villiger(Eric, 32, male, playing guitar)
p3 = Villiger(Anna, 10, female, running)
p4 = Villiger(Rick, 70, male, crafting)

The process of creating a class and putting init function might be a bit complicated, but once you've created a class, you can see that now the data is much more organized and easier to see.

Now, when you want to extract data from each instance, you just code:

print(p1._name, p1._hobby)
print(p3._age)

Something like this.

Now, for people who are first encountering init or ._variables, you can just run this code after creating a class:

class Example():

print(Example.__dir__)

This will show you what kind of BUILT-IN functions and variables are in the class Example. Some of them are add (you can trigger them by using +) mul (*) init (Class name()) sub (-) and much more. In this article, I'll just talk about init, since there are tons of tutorials for other functions and there are too many to go over all of them.

init

init functions create variables inside the class and assign the variables you've inputted. so for the example above:

class Villiger(): 
    def __init__(self, name, age, sex, hobby)
        self._name = name
        self._age = age
        self._sex = sex
        self._hobby = hobby

p1 = Villiger(Josh, 18, male, reading)

In the function init inside the Villiger, it creates a variable called _name and assigns it the first variable the user inputted. (ignore the self but get into the habit of always writing self FIRST inside the parenthesis.) It creates a variable called _age and assigns it the second variable the user inputted. And it goes on.

These are the basics of Classes. I've only dealt with init functions as they are used in 99% of the classes that developers make. get into the habit of organizing data, creating classes, and making init functions effectively.

Happy Coding!