Everything a Beginner should know about Classes and Objects in Python Before Starting Your Data Science Journey[With Examples]
This article was published as a part of the Data Science Blogathon
OOP, or Object-Oriented Programming, is a programming paradigm that uses objects and classes to create functional programs. OOPs focus on code modularity, and classes and objects aid in the creation of reusable, simple pieces of code that can be used to build larger software features and modules. The three most popular Object-Oriented Programming languages are C++, Java, and Python. However, when it comes to today’s use cases – such as Data Science and Statistical Analysis – Python takes the lead over the other two.
This is not surprising given that data scientists worldwide rely on the Python programming language’s capabilities. Knowing about classes and objects should be your priority if you want to start a career in Data Science and master Python.
This article will help you understand the nuances of Python objects and classes and how to start creating and working with your own classes.
Classes in Python
In Python, a class is a user-defined prototype from which objects are created. In simple terms, a class is a method for grouping data and functionality. The importance of the two keywords cannot be overstated. Any variables that have been instantiated or defined are referred to as data, and any operation that can be performed on that data is referred to as functionality. Classes are created when data and functionality are bundled into a single package.
Consider the following simple example to understand the importance of creating a class. Assume you want to keep track of dogs in your neighborhood that have different characteristics such as age, breed, color, weight, and so on. You can use a list to track elements in a 1:1 relationship, for example, tracking the breed to the age or the age to the weight. What if there are supposed to be a hundred different kinds of cats? What if more properties need to be added? Using lists in this situation is unorganized and messy.
That is where classes come into play!
Classes assist you in developing a user-defined data structure with its own data members (variables) and member functions. You can access these variables and methods by simply creating an object for the class (we’ll go over this in more detail later). In that sense, classes are similar to a blueprint for an object.
Furthermore, creating classes creates a new type of object – allowing you to create more objects of the same type. In order to maintain its state, each class instance can have attributes attached to it. Class instances can have methods for modifying the state (as defined by their class).
Some points on Python class:
Using the keyword class, classes are created.
Attributes are the variables that are specific to the class you created.
These attributes are always public and can be accessed by inserting a dot after the class name. For instance, “ClassName. AttributeName” will return the specific attribute detail for that class.
Syntax for defining a class-
class ClassName: # Statement-1 . . . . # Statement-N
# Python3 program to # demonstrate defining # a class class Dog: pass
In the previous example, the class keyword indicates that you are creating a class, followed by the class name (Dog in this case).
Advantages of using Classes in Python
· Classes help you in keeping all of the various types of data properly organised in one place. You are keeping the code clean and modular in this manner, which improves the readability of your code.
· Using classes enables you to take advantage of another OOP paradigm known as inheritance. This occurs when one class inherits the properties of another.
· Classes give you the ability to override any standard operators.
· Classes make your code reusable, which improves the efficiency of your programme.
Objects in Python
An object is simply a subclass of any class you’ve defined. When you create a class, an automatic instance is created. As shown in the example, the dog class automatically creates an object that looks like a real dog – a German Shepherd dog that is three years old. There can be many different instances of dogs having different properties, but for it to make sense, you’ll need a class to guide you. Otherwise, you’ll be puzzled, unsure of what information is required.
There are three main features in an object:
· State: This refers to the different attributes and properties of every object.
· Behaviour: This essentially indicates the object’s methods. It also reflects the interaction or response to other objects by this particular object.
· Identity: Identity is the unique name of the object to be invoked as needed.
Declaring Objects is also called the instantiation of a class, as a default item is created in itself when you define a class (as we have previously seen) – which is the class instance. Similarly, you are creating a new instance for your class every time you create an object.
In terms of the three things we mentioned earlier (state, behavior, identity), all cases (objects) share different responses and conditions, however. Any number of objects can be in one class, as the programmer requires.
class dog: # A simple class # attribute attr1 = “Canidae” attr2 = “dog” # A sample method def fun(self): print(“I’m a”, self.attr1) print(“I’m a”, self.attr2) # Driver code # Object instantiation Bruno = dog() # Accessing class attributes # and method through objects print(Bruno.attr1) Bruno.fun();
The output of this simple program will be as follows: Canidae I’m a Canidae I’m a dog
As you can see, we first created a class called the dog and then instantiated an object with the name ‘bruno.’ The three outputs we got were as follows:
Canidae – this was the result of the statement print(Bruno.attr1). Since Bruno is an object of the dog class and attr1 has been set as Canidae, this function returns the output Canidae.
I’m a Canidae – Bruno. fun(); uses the object called Bruno to invoke a function in the dog class, known as ‘fun’. The Bruno object brings with it the attributes to the function, and therefore the function outputs the following two sentences – “I’m a Canidae”.
I’m a dog – same reason as stated above.
Let’s now look at some important methods, as you understand how classes and objects work in Python.
The Self Method
An additional first parameter in the function definition shall be required for all methods defined in any class. No value is assigned by the programmer to this parameter. But Python gives it a value when the method is called.
As a result, it still has a technical argument if you define a function without arguments. In Python, that is called “self.” You can review your C++ concept or reference it in Java in order to better understand this. The self-method works basically in the same way.
To understand this better let’s take an example
myObject.myMethod(arg1, arg2), Python automatically transform it into myClass.myMethod(myObject, arg1, arg2).
As you can see, the object itself becomes the method’s first argument. That’s what Python’s self is all about.
The __init__ method
This procedure is similar to Java or C++ builders. The init method is used, as the builders, to initialize the state of an object. This includes a collection of instructions (statements) executed during the creation of the object. When an object for a class is instantiated, the init method automatically executes the methods you initialize.
Here is a code piece for better understanding:
# A Sample class with init method class Person: # init method or constructor def __init__(self, name): self.name = name # Sample Method def say_hi(self): print(‘Hello, my name is’, self.name) p = Person(“Yash”) p.say_hi() Output: Hello, my name is Yash
Class and Instance Variables
Instance variables are unique per each instance, while class variables are for methods and attributes shared by all the instances of a class. Consequently, instance variables are variables whose value is given inside a constructor or a method with self. On the other hand, class variables are those whose values are given within a class.
Go through the following code for a better understanding
class dog: # Class Variable animal = ‘dog’ # The init method or constructor def __init__(self, breed, color): # Instance Variable self.breed = breed self.color = color # Objects of Dog class Bruno = dog(“Siberian Husky”, “black and white”) Oscar = dog(“German Shepherd”, “black and tan”) print(“Bruno details:’) print(‘Bruno is a’, Bruno.animal) print(‘Breed: ‘,Bruno.breed) print(‘Color: ‘,Bruno.color) print(‘nOscar details:’) print(“Oscar is a’, Oscar.animal) print(‘Breed: ‘,Oscar.breed) print(‘Color: ‘,Oscar.color)
Output: Bruno details: Bruno is a dog Breed: Siberian Husky Color: black and white Oscar details: Oscar is a dog Breed: German Shepherd Color: black and tan
Python is a relatively easy programming language, especially for beginners. Once you have mastered the basics of it, you’ll be able to work with various Python libraries and solve data-specific problems. However, keep in mind that while understanding classes and objects is the first step, you must also learn how to work with various objects, classes, and their nuances.
I hope this article helped clarify your doubts about classes and objects in Python.
About The Author
Currently, I Am pursuing my Bachelors of Technology( B.Tech) from Vellore Institute of Technology. I am very enthusiastic about programming and its real applications including software development, machine learning, and data science.
Hope you like the article. If you want to connect with me then you can connect on:
or for any other doubts, you can send a mail to me also