Publish AI, ML & data-science insights to a global community of data professionals.

Classes in Python

Understanding Object Oriented Programming

Source
Source

Classes allow us to organize data and functions in a way that makes them easy to reuse and extend in the future. In this post, we will discuss the basics of building classes in python.

Let’s get started!

To start, let’s create a simple class that represents Spotify Users, with no data (also called attributes) or functions (also called methods):

class Spotify_User:
    pass

Now, let’s take some time to distinguish between classes and instances of classes. A class is basically a blueprint for creating instances. Each unique user we create will be an instance of the Spotify_User class. For example, I can define two Spotify user instances, user_1 and user_2:

user_1 = Spotify_User()
user_2 = Spotify_User()

Each of these users will be their own unique instances of the Spotify_User class. We can print both objects:

print(user_1)
print(user_2)

We see that both of these are Spotify_User objects with different memory addresses. Another thing we can do is create instance variables, which are variables unique to each instance. Let’s define instance variables that hold the names of each user:

user_1.name = 'Sarah Phillips'
user_2.name = 'Todd Grant'

Let’s also give each instance an email:

user_1.email = '[email protected]'
user_2.email = '[email protected]'

Finally let’s define instance variables that tell us whether or not each user is a premium Spotify member:

user_1.premium = True
user_2.premium = False

Now each of these instances have attributes that are unique to each instance. Let’s print each users name:

print(user_1.name)
print(user_2.name)

Ideally, we’d like to set all of this information for each user automatically, instead of setting these values manually. To get the full benefit of classes, we should define a method that allows us to initialize each user instance with the values we defined manually. The initialization method, which is basically a constructor, is going to be called ‘init‘:

class Spotify_User:
    def __init__(self, name, email, premium):
        self.name = name
        self.email = email
        self.premium = premium

Here, the ‘self’ parameter is the instance and is what will allows us to share attribute information within the instance. For example, when we write:

user_1 = Spotify_User('Sarah Phillips', '[email protected]', True)
user_2 = Spotify_User('Todd Grant', '[email protected]', False)

the ‘self’ parameters in each case are the user_1 and user_2 objects respectively. If we print the emails we see:

print(user_1.email)
print(user_2.email)

This allows us to define attributes with significantly less code than when we defined them manually. Now suppose we’d like to perform some operation on the attributes of each user. For example, we can define a method that tells us whether or not a user has a premium membership. In our method, we print "User is a Premium Spotify User", if ‘self.premium’ is True, otherwise, we print "User is not a Premium Spotify User":

def isPremium(self):
        if self.premium:
            print("{} is a Premium User".format(self.name))
        else:
            print("{} is not a Premium User".format(self.name))

Let’s call the method using the user_1 instance:

user_1.isPremium()

And on user_2:

user_2.isPremium()

As you can see, since the ‘self’ parameter is passed to ‘init‘ and ‘isPremium’, upon initialization the ‘isPremium’ method has full access to the attributes of the corresponding instance.

I’ll stop here but feel free to play around with the code. For example, you can try defining a few additional user instances of the Spotify_User class. From there you can practice pulling instance attributes and using the class method ‘isPremium’. Once you feel comfortable I encourage you to define additional class methods. An interesting method could be one that displays custom playlists for each user.

CONCLUSIONS

To summarize, in this post we discussed the basics of defining classes in python. We showed how to define instances of classes, initialize instances, access instance attributes, and manipulate attributes with methods. The code from this post is available on GitHub. Thank you for reading!


Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.

Write for TDS

Related Articles