Unit 4: Object
Oriented Programming with Python [10]
4.1 Class
and Object
4.2 __init__
method
4.3 self
keyword
4.4 Inheritance
4.5 Polymorphism and Data Hiding
Practical Works
• Write program to elaborate
object oriented concept with simple examples.
• Write program to make use
of __init__ method to initialize objects.
• Write program to apply
different types of inheritance.
• Write program to elaborate
polymorphism and data hiding concept.
4.1 Class and Object
Python Objects Classes
Python is an object-oriented programming language that
offers classes, which are a potent tool for writing reusable code. To describe
objects with shared characteristics and behaviours, classes are utilised. We
shall examine Python's ideas of classes and objects in this article.
Classes in Python:
In Python, a class is a user-defined data type that
contains both the data itself and the methods that may be used to manipulate
it. In a sense, classes serve as a template to create objects. They provide the
characteristics and operations that the objects will employ.
Suppose a class is a prototype of a building. A building
contains all the details about the floor, rooms, doors, windows, etc. we can
make as many buildings as we want, based on these details. Hence, the building
can be seen as a class, and we can create as many objects of this class.
Creating Classes in Python
In Python, a class can be created by using the keyword
class, followed by the class name. The syntax to create a class is given below.
Syntax
- class ClassName:
- #statement_suite
In Python, we must notice that each class is associated
with a documentation string which can be accessed by using <class-name>.__doc__.
A class contains a statement suite including fields, constructor, function,
etc. definition.
Example:
Code:
class Person:
def __init__(self, name, age):
# This is the constructor method that is called when creating a new Person object
# It takes two parameters, name and age, and initializes them as attributes of the object
self.name = name
self.age = age
def greet(self):
# This is a method of the Person class that prints a greeting message
print("Hello, my name is " + self.name)
Name and age are the two properties of the Person class.
Additionally, it has a function called greet that prints a greeting.
Objects in Python:
An object is a particular instance of a class with
unique characteristics and functions. After a class has been established, you
may make objects based on it. By using the class constructor, you may create an
object of a class in Python. The object's attributes are initialised in the
constructor, which is a special procedure with the name __init__.
Syntax:
- # Declare an object of a class
- object_name = Class_Name(arguments)
Example:
Code:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is " + self.name)
# Create a new instance of the Person class and assign it to the variable person1
person1 = Person("Ayan", 25)
person1.greet()
Output:
"Hello, my name is Ayan"
4.2 __init__ method
In order to make an instance of a class in Python, a
specific function called __init__ is called. Although it is used to set the
object's attributes, it is often referred to as a constructor.
The self-argument is the only one required by the
__init__ method. This argument refers to the newly generated instance of the
class. To initialise the values of each attribute associated with the objects,
you can declare extra arguments in the __init__ method.
Class and Instance Variables
All instances of a class exchange class variables. They
function independently of any class methods and may be accessed through the use
of the class name. Here's an illustration:
Code:
- class Person:
- count = 0 # This is a class variable
-
- def __init__(self, name, age):
- self.name = name # This is an instance variable
- self.age = age
- Person.count += 1 # Accessing the class variable using the name of the class
- person1 = Person("Ayan", 25)
- person2 = Person("Bobby", 30)
- print(Person.count)
Output:
2
Whereas, instance variables are specific to each
instance of a class. They are specified using the self-argument in the __init__
method. Here's an illustration:
Code:
- class Person:
- def __init__(self, name, age):
- self.name = name # This is an instance variable
- self.age = age
- person1 = Person("Ayan", 25)
- person2 = Person("Bobby", 30)
- print(person1.name)
- print(person2.age)
Output:
Ayan
30
Class variables are created separately from any class
methods and are shared by all class copies. Every instance of a class has its
own instance variables, which are specified in the __init__ method utilising
the self-argument.
4.3 self keyword
The self represents the class instance. We may access
the class's properties and methods in Python using the "self"
keyword. The keyword associates the properties with the class's arguments
provided.
Since Python does not employ the @ syntax to create
references to the instance attributes, we must use self. Python opted to
implement methods so that the instance of the classes to which the method
corresponds is automatically supplied but not immediately received: the first
argument of any method is the instance on which the method is executed.
Exploring Object references with self
Example 1 : self keyword program
Code
- # Python program to show the use of the self keyword
-
- class Class:
- def __init__(self):
- print("The reference id of the self method is: ",id(self))
-
- # Creating an instance of the class
- obj = Class()
- print("The reference id of the object is: ",id(obj))
Output
The reference id of the self method is: 139904481668400
The reference id of the object is: 139904481668400
4.4 Inheritance
In inheritance, the child class acquires the
properties and can access all the data members and functions defined in the
parent class. A child class can also provide its specific implementation to the
functions of the parent class. In this section of the tutorial, we will discuss
inheritance in detail.
In python, a derived class can inherit base
class by just mentioning the base in the bracket after the derived class name.
Consider the following syntax to inherit a base class into the derived class.
Python Inheritance
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by
mentioning all of them inside the bracket. Consider the following syntax.
Syntax
class derive-class(<base class 1>, <base class 2>, .....
<base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d
= Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
Python Multi-Level inheritance
Multi-Level inheritance is possible in python
like other object-oriented languages. Multi-level inheritance is archived when
a derived class inherits another derived class. There is no limit on the number
of levels up to which, the multi-level inheritance is archived in python.
The syntax of multi-level inheritance is
given below.
Syntax
- class class1:
- <class-suite>
- class class2(class1):
- <class suite>
- class class3(class2):
- <class suite>
- .
- .
Example
- class Animal:
- def speak(self):
- print("Animal Speaking")
- #The child class Dog inherits the base class Animal
- class Dog(Animal):
- def bark(self):
- print("dog barking")
- #The child class Dogchild inherits another child class Dog
- class DogChild(Dog):
- def eat(self):
- print("Eating bread...")
- d = DogChild()
- d.bark()
- d.speak()
- d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Python Multiple inheritance
Python provides us the flexibility to
inherit multiple base classes in the child class.
The syntax to perform multiple inheritance
is given below.
Syntax
- class Base1:
- <class-suite>
-
- class Base2:
- <class-suite>
- .
- .
- .
- class BaseN:
- <class-suite>
-
- class Derived(Base1, Base2, ...... BaseN):
- <class-suite>
Example
- class Calculation1:
- def Summation(self,a,b):
- return a+b;
- class Calculation2:
- def Multiplication(self,a,b):
- return a*b;
- class Derived(Calculation1,Calculation2):
- def Divide(self,a,b):
- return a/b;
- d = Derived()
- print(d.Summation(10,20))
- print(d.Multiplication(10,20))
- print(d.Divide(10,20))
Output:
30
200
0.5
4.5
Polymorphism and Data Hiding
Polymorphism
refers to having multiple forms. Polymorphism is a programming term that refers
to the use of the same function name, but with different signatures, for
multiple types.
Example
of in-built polymorphic functions:
- # Python program for demonstrating the in-built poly-morphic functions
-
- # len() function is used for a string
- print (len("Javatpoint"))
-
- # len() function is used for a list
- print (len([110, 210, 130, 321]))
Output:
10
4
Examples
of user-defined polymorphic functions:
- # here, is a simple Python function
- # for demonstrating the Polymorphism
-
- def add(p, q, r = 0):
- return p + q + r
-
- # Driver code
- print (add(6, 23))
- print (add(22, 31, 544))
Output:
29
597
Polymorphism
with Class Methods
Below
is an example of how Python can use different types of classes in the same way.
For loops that iterate through multiple objects are created. Next, call the
methods without caring about what class each object belongs to. These methods
are assumed to exist in every class.
Example:
- class xyz():
- def websites(self):
- print("Javatpoint is a website out of many availabe on net.")
-
- def topic(self):
- print("Python is out of many topics about technology on Javatpoint.")
-
- def type(self):
- print("Javatpoint is an developed website.")
-
- class PQR():
- def websites(self):
- print("Pinkvilla is a website out of many availabe on net. .")
-
- def topic(self):
- print("Celebrities is out of many topics.")
-
- def type(self):
- print("pinkvilla is a developing website.")
-
- obj_jtp = xyz()
- obj_pvl = PQR()
- for domain in (obj_jtp, obj_pvl):
- domain.websites()
- domain.topic()
- domain.type()
Output:
Javatpoint
is a website out of many availabe on net.
Python
is out of many topics about technology on Javatpoint.
Javatpoint
is an developed website.
Pinkvilla
is a website out of many availabe on net.
Celebrities
is out of many topics.
pinkvilla
is a developing website.
Polymorphism
with Inheritance:
Polymorphism
allows us to define methods in Python that are the same as methods in the
parent classes. In inheritance, the methods of the parent class are passed to
the child class. It is possible to change a method that a child class has
inherited from its parent class. This is especially useful when the method that
was inherited from the parent doesn't fit the child's class. We re-implement
such methods in the child classes. This is Method Overriding.
Example:
- class Birds:
- def intro1(self):
- print("There are multiple types of birds in the world.")
- def flight1(self):
- print("Many of these birds can fly but some cannot.")
-
- class sparrow1(Birds):
- def flight1(self):
- print("Sparrows are the bird which can fly.")
-
- class ostrich1(Birds):
- def flight1(self):
- print("Ostriches are the birds which cannot fly.")
-
- obj_birds = Birds()
- obj_spr1 = sparrow1()
- obj_ost1 = ostrich1()
-
- obj_birds.intro1()
- obj_birds.flight1()
-
- obj_spr1.intro1()
- obj_spr1.flight1()
-
- obj_ost1.intro1()
- obj_ost1.flight1()
Output:
There
are multiple types of birds in the world.
Many
of these birds can fly but some cannot.
There
are multiple types of birds in the world.
Sparrows
are the bird which can fly.
There
are multiple types of birds in the world.
Ostriches
are the birds which cannot fly.
Data
hiding is a part of object-oriented programming, which is generally used to
hide the data information from the user. It includes internal object details
such as data members, internal working. It maintained the data integrity and
restricted access to the class member. The main working of data hiding is that
it combines the data and functions into a single unit to conceal data within a
class. We cannot directly access the data from outside the class.
This
process is also known as the data encapsulation. It is done by hiding
the working information to user. In the process, we declare class members as
private so that no other class can access these data members. It is accessible
only within the class.
Data Hiding in Python
Python is the most
popular programming
language as it applies in every technical domain and has a straightforward
syntax and vast libraries. In the official Python documentation, Data hiding
isolates the client from a part of program implementation. Some of the
essential members must be hidden from the user. Programs or modules only
reflected how we could use them, but users cannot be familiar with how the
application works. Thus it provides security and avoiding dependency as well.
We
can perform data hiding in Python using the __ double underscore before prefix.
This makes the class members private and inaccessible to the other classes.
Let's
understand the following example.
Example -
- class CounterClass:
- __privateCount = 0
- def count(self):
- self.__privateCount += 1
- print(self.__privateCount)
- counter = CounterClass()
- counter.count()
- counter.count()
- print(counter.__privateCount)
Output:
1
2
Traceback
(most recent call last):
File "<string>", line 17, in
<module>
AttributeError:
'CounterClass' object has no attribute '__privateCount'
However
we can access the private member using the class name.
- print(counter.CounterClass__privatecounter)
Output:
1
2
2
No comments:
Post a Comment