Enhance your Python Project Code with Classes

Original article was published by Marco Santos on Artificial Intelligence on Medium

Class Methods (Functions)

Functions that we create within a class are called methods. Functions and methods are essentially the same thing but in the context of class objects, functions are referred to as methods. We will need to create some methods for our class in order to manipulate and utilize the data given.

In this case we will be using a synthetic dataset of dating profiles we created earlier before. See the following article to see the creation of this dataset:

This dataset will give us the context from which we will create a new dating profile.

Creating a New Dating Profile with a Class Method

One of the first things we want our class to do is to create a brand new profile if it wasn’t already provided with one. To do this we can create a new method below the __init__ method:

class createProfile:
def __init__(self,
self.dataset = dataset
self.profile = profile

def enter_info(self):
# Code goes here

As you can see, we are still using the self argument. We will need it as we type in the rest of the code:

The above method uses self throughout the code. When we use self.profile, we are referring to the attribute we had assigned in the __init__ method. First, we are checking to see if it is an empty DataFrame, which it is. Next, we will use the self.dataset variable we had also assigned in the __init__ method and use its features to create the new profile.

We allow the option to either use random information from the larger dataset to fill in the new profile or enter information manually. After having the profile information entered, the method overwrites the self.profile attribute with the new profile information. If you were to try to run this method again, it will return the string: “Data already contained in the profile.

If you wanted to enter new information, you’ll have to reinstantiate the class and run it again from the top. Instantiating the class starts the whole process all over again.

Running the Class Method

Here is how we run this method starting from the instantiation step:

# Instantiating with the data from the DF of synthetic profiles
new_profile = createProfile(dataset=data)
# Running the method

That is really all we need. Just the two lines of code. When we run this it will either enter random information for the profile, which is the function’s default behavior, or it will prompt us to enter information manually like so: