Oops in Python
Oops in Python
Class
A class is a collection of objects. A class contains the blueprints or the prototype from
which the objects are being created. It is a logical entity that contains some attributes and
methods.
To understand the need for creating a class let’s consider an example, let’s say you
wanted to track the number of dogs that may have different attributes like breed, age. If a
list is used, the first element could be the dog’s breed while the second element could
represent its age. Let’s suppose there are 100 different dogs, then how would you know
which element is supposed to be which? What if you wanted to add other properties to
these dogs? This lacks organization and it’s the exact need for classes.
Some points on Python class:
Python
# Python3 program to
# demonstrate defining
# a class
class Dog:
pass
In the above example, we have created a class named dog using the class keyword.
Objects
The object is an entity that has a state and behavior associated with it. It may be any real-
world object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point
numbers, even arrays, and dictionaries, are all objects. More specifically, any single
integer or any single string is an object. The number 12 is an object, the string “Hello,
world” is an object, a list is an object that can hold other objects, and so on. You’ve been
using objects all along and may not even realize it.
An object consists of :
State: It is represented by the attributes of an object. It also reflects the properties of
an object.
Behavior: It is represented by the methods of an object. It also reflects the response
of an object to other objects.
Identity: It gives a unique name to an object and enables one object to interact with
other objects.
To understand the state, behavior, and identity let us take the example of the class dog
(explained above).
The identity can be considered as the name of the dog.
State or Attributes can be considered as the breed, age, or color of the dog.
The behavior can be considered as to whether the dog is eating or sleeping.
Example: Creating an object
Python3
obj = Dog()
This will create an object named obj of the class Dog defined above. Before diving deep
into objects and class let us understand some basic keywords that will we used while
working with objects and classes.
The self
1. Class methods must have an extra first parameter in the method definition. We do not
give a value for this parameter when we call the method, Python provides it
2. If we have a method that takes no arguments, then we still have to have one argument.
3. This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is
automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this is
all the special self is about.
Note: For more information, refer to self in Python class
Example 1: Creating a class and object with class and instance attributes
Python3
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
self.name = name
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
print("Rodger is a {}".format(Rodger.__class__.attr1))
Output
Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy
Python3
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
self.name = name
def speak(self):
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
Rodger.speak()
Tommy.speak()
Output
My name is Rodger
My name is Tommy
Note: For more information, refer Python Classes and Objects
Inheritance
Inheritance is the capability of one class to derive or inherit the properties from another
class. The class that derives properties is called the derived class or base class and the
class from which the properties are being derived is called the base class or parent class.
The benefits of inheritance are:
It represents real-world relationships well.
It provides the reusability of a code. We don’t have to write the same code again and
again. Also, it allows us to add more features to a class without modifying it.
It is transitive in nature, which means that if class B inherits from another class A,
then all the subclasses of B would automatically inherit from class A.
Python3
# are called.
# parent class
class Person(object):
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("IdNumber: {}".format(self.idnumber))
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
def details(self):
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))
# its instance
a.display()
a.details()
Output
Rahul
886012
My name is Rahul
IdNumber: 886012
Post: Intern
In the above article, we have created two classes i.e. Person (parent class) and Employee
(Child Class). The Employee class inherits from the Person class. We can use the
methods of the person class through employee class as seen in the display function in the
above code. A child class can also modify the behavior of the parent class as seen
through the details() method.
Note: For more information, refer to our Inheritance in Python tutorial.
Polymorphism
Polymorphism simply means having many forms. For example, we need to determine if
the given species of birds fly or not, using polymorphism we can do this using a single
function.
Python3
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
class sparrow(Bird):
def flight(self):
class ostrich(Bird):
def flight(self):
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
Output
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
Note: For more information, refer to our Polymorphism in Python Tutorial.
Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented programming
(OOP). It describes the idea of wrapping data and the methods that work on data within
one unit. This puts restrictions on accessing variables and methods directly and can
prevent the accidental modification of data. To prevent accidental change, an object’s
variable can only be changed by an object’s method. Those types of variables are known
as private variables.
A class is an example of encapsulation as it encapsulates all the data that is member
functions, variables, etc.
Python3