Class and Objects
Class and Objects
Hindi #59
Our today's tutorial is based mainly on theory because coding is not just
about learning new concepts but also about understanding them. Let us
give our PyCharm some rest and try to learn some theory about
Abstraction and Encapsulation, which are fundamental concepts for our
tutorials ahead.
What is Abstraction?
Abstraction refers to hiding unnecessary details to focus on the whole
product instead of parts of the project separately. It is a mechanism that
represents the important features without including implementation
details. Abstraction helps us in partitioning the program into many
independent concepts so we may hide the irrelevant information in the
code. It offers the greatest flexibility when using abstract data-type
objects in different situations.
Example of Abstraction:
Let us take the example of a car. It has an engine, tires, windows,
steering wheel, etc. All these things combine to form a car, which is an
abstraction, and all the different parts are its layers of abstraction. Now
an engine is composed of various parts such as camshaft, valves, oil
pan, etc. these flayers the engine is an abstraction. In simple words,
abstraction can be achieved by hiding the background details and
showing only the necessary ones. In programming, abstraction can not
be achieved without Encapsulation.
What is Encapsulation?
Encapsulation means hiding under layers. When working with classes
and handling sensitive data, global access to all the variables used in
the program is not secure. In Encapsulation, the internal representation
of an object is generally hidden from the outside to secure the data. It
improves the maintainability of an application and helps the developers
to organize the code better.
Example of Encapsulation
We can take an example of a capsule in which the medicine is
encapsulated. We have often used examples of bigger projects in which
many programmers contribute according to their tasks. In the end, the
whole project is done by joining the contribution of each participant. Well,
this is what Encapsulation aims to achieve.
Abstraction Encapsulation
Encapsulation is used to solve the
Abstraction is used to solve the problem
problem and issue that arise at the
and issues that arise at the design stage.
implementation stage.
Abstraction focuses on what the object Encapsulation focuses on hiding the code
does instead of how the details are and data into a single unit to secure the
implemented. data from the outside world.
Encapsulation can be implemented using
Abstraction can be implemented by
Access Modifiers (Public, Protected, and
using Interface and Abstract Class.
Private.)
Its application is during the design Its application is during the
level. Implementation level.
This tutorial is all about understanding the concept of Abstraction and
Encapsulation. Check the next tutorials to learn how to implement more
OOP concepts in Python.
Syntax:
class Parent_class_Name:
#Parent_class code block
class Child_class_Name(Parent_class_name):
#Child_class code block
Copy
The above syntax consists of two classes declared. One is the parent
class or by other means, the base class, and the other one is the child
class which acts as the derived class.
Parent: The parent class is the one that is giving access to its
methods or properties to the child class or derived class.
Child: Child class is the one that is inheriting methods and
properties from the parent class.
The class that is inheriting, i.e., the child class, can inherit all the
functionality of the parent class and add its functionalities also. As we
have already discussed that each class can have its constructors and
methods, so in case of inheritance the child class can make and use its
constructor and also can use the constructor of the parent class. We can
simply construct it as we did for the parent class but OOP has provided
us with a simple and more useful solution known as Super().
Single inheritance exists when a class is only derived from a single base
class. Or in other words when a child class is using the methods and
properties of only a single parent class then single inheritance exists.
Single inheritance and Multiple inheritance are very similar concepts, the
only major difference is the number of classes. We will see Multiple
Inheritance in our next tutorial.
class Child(Parent):
def second(self):
print('Child function')
object1 = Child()
object1.first()
object1.second()
Copy
Output:
Parent function
Child function
Copy
Advantages of Inheritance:
class Employee:
no_of_leaves = 8
def printdetails(self):
return f"The Name is {self.name}. Salary is {self.salary}
and role is {self.role}"
@classmethod
def change_leaves(cls, newleaves):
cls.no_of_leaves = newleaves
@classmethod
def from_dash(cls, string):
return cls(*string.split("-"))
@staticmethod
def printgood(string):
print("This is good " + string)
While using the concept of multiple inheritance, the order of placing the
base classes is very important. Let us clear the concept using an
example. Suppose we have a child class named Child, and it has two
base classes, named Base1 and Base2.
Example:
class Base1:
def func1(self):
print("this is Base1 class")
class Base2:
def func2(self):
print("this is Base2 class")
obj = Child()
obj.func1()
obj.func2()
obj.func3()
Copy
Output:
Method Overriding:
Override means having two methods that have the same name. They
may perform same tasks or different tasks. In python, when the same
method defined in the parent class is also defined in the child class, the
process is known as Method overriding. This is also true when multiple
classes have the same method and are linked together somehow.
There are few rules for Method overriding that should be followed:
In this case, the child method will run, and the reason for which, we have
discussed in the paragraph above, related to ordering. Multiple
inheritance is based on the same concept on which the single
inheritance is based on i.e., DRY (do not repeat yourself). Multiple
inheritance makes it easier to inherit methods and attributes from base
classes that implement the functionality. When done right, we can reuse
the code without having to copy-and-paste a similar code to implement
interfaces.
class Employee:
no_of_leaves = 8
var = 8
def printdetails(self):
return f"The Name is {self.name}. Salary is {self.salary}
and role is {self.role}"
@classmethod
def change_leaves(cls, newleaves):
cls.no_of_leaves = newleaves
@classmethod
def from_dash(cls, string):
return cls(*string.split("-"))
@staticmethod
def printgood(string):
print("This is good " + string)
If we have the same method or variable in the base and derived class,
then the order we discussed above will be followed, and the method will
be overridden. Else, if the child class does not contain the same method,
then the derived1 class method will be followed by the sequence defined
in the paragraph above.
For Example:
class level1:
def first(self):
print ('code')
obj=level3()
obj.first()
obj.second()
obj.third()
Copy
Advantages of Inheritance
class Dad:
basketball =6
class Son(Dad):
dance =1
basketball = 9
def isdance(self):
return f"Yes I dance {self.dance} no of times"
class Grandson(Son):
dance =6
guitar = 1
def isdance(self):
return f"Jackson yeah!" \
f"Yes I dance very awesomely {self.dance} no of times"
darry = Dad()
larry = Son()
harry = Grandson()
# print(darry.guitar)
# electronic device
Public, Private & Protected Access Specifiers | Python Tutorials For Absolute
Beginners In Hindi #63
Access modifiers are used for the restrictions of access any other class
has on the particular class and its variables and methods. In other
words, access modifiers decide whether other classes can use the
variables or functions of a specific class or not. The arrangement of
private and protected access variables or methods ensures the principle
of data encapsulation. In Python, there are three types of access
modifiers.
# Public -
# Protected -
# Private -
class Employee:
no_of_leaves = 8
var = 8
_protec = 9
__pr = 98
def printdetails(self):
return f"The Name is {self.name}. Salary is {self.salary}
and role is {self.role}"
@classmethod
def change_leaves(cls, newleaves):
cls.no_of_leaves = newleaves
@classmethod
def from_dash(cls, string):
return cls(*string.split("-"))
@staticmethod
def printgood(string):
print("This is good " + string)
What Is Polymorphism?
In the basic English language, Polymorphism means to exist in different
states. The same object or thing changing its state from one form to
another is known as polymorphic. The same function or method, being
used differently in different scenarios, can perfectly describe
Polymorphism. It occurs mostly with base and derived classes.
For example:
len("Python") # returns 6 as result
len([1,2,3,4,5,6,7,8,9]) # returns 9 as result
Copy
Python also implements Polymorphism using methods. The len() method
returns the length of an object. In this case, the function len() is
polymorphic as it is taking a string as input in the first case, which
returns the total length/characters of the string, and in the second case,
it is taking list as input.
class Child_Class(Parent_Class):
def __init__(self):
super().__init__()
Copy
super() returns a temporary object of the superclass that then allows you
to call that superclass’s methods. The primary use case of super() is to
extend the functionality of the inherited method.
class B(A):
classvar1 = "I am in class B"
def __init__(self):
self.var1 = "I am inside class B's constructor"
self.classvar1 = "Instance var in class B"
# super().__init__()
# print(super().classvar1)
a = A()
b = B()