The world’s leading publication for data science, AI, and ML professionals.

Getting Started with Python Classes

Object Oriented Programming in Python

Photo by Christina Morillo on Pexels
Photo by Christina Morillo on Pexels

In computer Programming, classes are a convenient way to organize data and functions such that they are easy to reuse and extend later. In this post, we will walk through how to build a basic class in python. Specifically, we will discuss the example of implementing a class that represents instagram users.

Let’s get started!

To start, let’s define a simple class that represents Instagram Users. Initially we won’t include any data (attributes) or functions (methods):

class Instagram_User:
    pass

Two import concepts to understand in object-oriented program are classes and class instances. A user of the Instagram platform can be considered an instance of the ‘Instagram_User’ class. The distinction here is that the ‘Instagram_User’ class serves as a blueprint for creating Instagram users, and an instance of the ‘Instagram_User’ class may refer to a specific user. To see this, we can define two Instagram user instances, insta_user_1 and insta_user_2:

insta_user_1 = Instagram_User()
insta_user_2 = Instagram_User()

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

print("User Object 1: ", insta_user_1)
print("User Object 2: ", insta_user_2)

Here we can see that each object has a unique memory address. Next thing we can do is create variables for each instance. Let’s define instance variables that holds the user name of each user:

insta_user_1.user_name = 'nychef100'
insta_user_2.user_name = 'worldtraveler123'

We can also define the name of each user:

insta_user_1.name = 'Jake Cohen'
insta_user_2.name = 'Maria Lopez'

the email address:

insta_user_1.email = '[email protected]'
insta_user_2.email = '[email protected]'

Finally let’s define an instance variable that tells us whether or not each user has a private account:

insta_user_1.private = True
insta_user_2.private = False

Now each instance has attribute values unique to each user. Let’s print the user names:

print(insta_user_1.user_name)
print(insta_user_2.user_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 Instagram_User:
    def __init__(self, user_name, name, email, private):
        self.user_name = user_name
        self.name = name
        self.email = email
        self.private = private

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:

insta_user_1 = Instagram_User('nychef100', 'Jake Cohen', '[email protected]', True)
insta_user_2 = Instagram_User('worldtraveler123', 'Maria Lopez', '[email protected]', False)

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

print(insta_user_1.email)
print(insta_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 private account. In our method, we print "User has a Private Account", if ‘self.private’ is True, otherwise, we print "User has a Public Account":

def isPrivate(self):
        if self.private:
            print("{} has a Private Account".format(self.name))
        else:
            print("{} has a Public Account".format(self.name))

The full script should look as follows:

class Instagram_User:
    def __init__(self, user_name, name, email, private):
        self.user_name = user_name
        self.name = name
        self.email = email
        self.private = private
    def isPrivate(self):
        if self.private:
            print("{} has a Private Account".format(self.name))
        else:
            print("{} has a Public Account".format(self.name))

Let’s call the method using the insta_user_1 instance:

insta_user_1.isPrivate()

And on insta_user_2:

insta_user_2.isPrivate()

As you can see, since the ‘self’ parameter is passed to ‘init‘ and ‘isPrivate’, upon initialization the ‘isPrivate’ 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 Instagram_User class. From there you can practice pulling instance attributes and using the class method ‘isPrivate’. Once you feel comfortable I encourage you to define additional class methods. An interesting method could be one that displays user metrics such as the number of followers, number of people a user follows, and number of posts.

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!


Related Articles