Object-Oriented Programming (OOP) is a paradigm employing classes and objects to build functional programs. Emphasizing code modularity, classes and objects craft reusable, compact code segments, forming the basis for comprehensive software features and modules. Leading OOP languages include C++, Java, and Python, excelling in today’s domains like Data Science and Statistical Analysis.
In Data Science, Python is a frontrunner due to its robust capabilities. Mastery of classes and objects is vital for aspirants venturing into Data Science, facilitating Python proficiency. Unlock insights into Python’s classes and objects with this article. Discover their intricacies and grasp the process of crafting and utilizing your unique classes. Your journey to OOP excellence begins here.
This article was published as a part of the Data Science Blogathon.
In Python, users define a class as a prototype for creating objects, serving as a means to group data and functionality. The significance of the two keywords is crucial. Variables instantiated or defined are termed data, and operations performed on that data are termed functionality. Creating classes involves bundling data and functionality 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).
class ClassName:
# Statement-1
.
.
.
.
# Statement-N
Example:
# 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).
Power up your career with the best and most popular data science language, Python. Enroll for our FREE course today!
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.
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();
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:
Let’s now look at some important methods, as you understand how classes and objects work in Python.
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.
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
Each instance has unique instance variables, whereas class variables are shared among all class instances. Instance variables receive values inside a constructor or a method with ‘self,’ while class variables have values specified 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
In Python, methods are essential for defining the behavior of objects created from classes. Methods encapsulate functionality, allowing objects to perform actions and interact with attributes. Let’s explore various types of methods that enrich the behavior of objects.
self
Instance methods are the most common type of method in Python classes. They operate on individual objects and have access to the object’s attributes via the self
parameter. This parameter refers to the instance calling the method, allowing the method to manipulate the object’s state.
Code:
class Circle:
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return 3.14 * self.radius ** 2
circle1 = Circle(5)
area = circle1.calculate_area()
print("Area of the circle:", area)
Output:
Area of the circle: 78.5
Special methods, also known as “magic” methods or dunder methods (double underscores), enable customizing the behavior of built-in Python operations. These methods follow specific naming conventions like __init__
, __str__
, and __add__
.
Code:
class ComplexNumber:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
new_real = self.real + other.real
new_imag = self.imag + other.imag
return ComplexNumber(new_real, new_imag)
num1 = ComplexNumber(3, 5)
num2 = ComplexNumber(2, 7)
sum_num = num1 + num2
print("Sum:", sum_num.real, "+", sum_num.imag, "i")
Output:
Sum: 5 + 12 i
@classmethod
Class methods are defined using the @classmethod
decorator and operate on the class itself rather than instances. They create alternative constructors or performing operations involving class-level attributes.
Code:
class Student:
total_students = 0
def __init__(self, name):
self.name = name
Student.total_students += 1
@classmethod
def get_total_students(cls):
return cls.total_students
student1 = Student("Alice")
student2 = Student("Bob")
total = Student.get_total_students()
print("Total students:", total)
Output:
Total students: 2
@staticmethod
Static methods are defined using the @staticmethod
decorator. They don’t have access to instance or class attributes and behave like regular functions within the class’s namespace.
Code:
class MathOperations:
@staticmethod
def multiply(a, b):
return a * b
result = MathOperations.multiply(5, 3)
print("Multiplication result:", result)
Output:
Multiplication result: 15
Getter and setter methods control access to attributes and allow validation or modification before setting values. Alternatively, Python supports properties, which provide a more elegant way to get, set, and delete attributes.
Code:
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Temperature cannot be below absolute zero.")
self._celsius = value
temp = Temperature(25)
print("Initial temperature:", temp.celsius)
temp.celsius = 30
print("Updated temperature:", temp.celsius)
Output:
Initial temperature: 25
Updated temperature: 30
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.
A. In Python, a class is a blueprint for creating objects with attributes (variables) and methods (functions) that define their behavior and properties.
A. The “object” class is the base class for all other classes in Python. Every class implicitly or explicitly inherits from this class.
A. The difficulty of a Python class depends on the curriculum, your background, and your learning approach. Beginners might find initial concepts easy, but complexity can increase with advanced topics.