1722964411-Python_Unit_5
1722964411-Python_Unit_5
# importing os module
import os
# Path
path = "./mypipe"
END OF UNIT-IV
UNIT V
OBJECT ORIENTED FEATURES: Classes Principles of Object Orientation - Creating
Classes - Instance Methods - File Organization - Special Methods - Class Variables Inheritance
Polymorphism - Type Identification - Simple Character Matches - Special Characters -
Character Classes Quantifiers - Dot Character - Greedy Matches Grouping - Matching at
Beginning or End - Match Objects Substituting - Splitting a String - Compiling Regular
Expressions. (10)
In the above example, have created a class named dog using the class keyword.
Page 116
PYTHON PROGRAMMING KG College of Arts and Science
class Dog:
pass
The body of the Dog class consists of a single statement: the pass keyword. pass is often used as
a placeholder indicating where code will eventually go. It allows you to run this code without
Python throwing an error.
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
g a b ec . T e be 12 a b ec , e g He , d a b ec , a
an object that can hold other objects, and so on.
An object consists of : (SBI)
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.
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 used while working with objects
and classes.
The self
1. Class methods must have an extra first parameter in the method definition. Value for this
parameter when the method is called , 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 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.
The __init__ method
The __init__ method is similar to constructors in C++ and Java. It is run as soon as an object
of a class is instantiated. The method is useful to do any initialization you want to do with your
object.
Now let us define a class and create some objects using the self and __init__ method.
Example 1: Creating a class and object with class and instance attributes
P 3
class Dog:
# class attribute
attr1 = "mammal"
Page 117
PYTHON PROGRAMMING KG College of Arts and Science
# Instance attribute
def __init__(self, name):
self.name = name
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Accessing class attributes
print("Rodger is a {}".format(Rodger.__class__.attr1))
print("Tommy is also a {}".format(Tommy.__class__.attr1))
# Accessing instance attributes
print("My name is {}".format(Rodger.name))
print("My name is {}".format(Tommy.name))
Output
Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy
#Example 2: Creating Class and objects with methods
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
def __init__(self, name):
self.name = name
def speak(self):
print("My name is {}".format(self.name))
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Accessing class methods
Rodger.speak()
Tommy.speak()
Output
My name is Rodger
My name is Tommy
Classes vs Instances :
Classes are used to create user-defined data structures. Classes define functions called methods,
which identify the behaviors and actions that an object created from the class can perform with
its data. Create a Dog class that stores some information about the characteristics and behaviors
that an individual dog can have.
Page 118
PYTHON PROGRAMMING KG College of Arts and Science
A class is a blueprint f e g d be def ed. I d e ac a c a a
data. The Dog class specifies that a name and an age are necessary for defining a dog, but it
doe c a e a e age f a ec f c d g.
While the class is the blueprint, an instance is an object that is built from a class and contains
real data. An instance of the Dog c a ab e a e. I a ac a d g a a e,
like M e , f ea d.
Put another way, a class is like a form or questionnaire. An instance is like a form that has been
filled out with information. Just like many people can fill out the same form with their own
unique information, many instances can be created from a single class.
Instantiate an Object in Python
O e IDLE e ac e d a d e ef g:
This creates a new Dog class with no attributes or methods. Creating a new object from a class is
called instantiating an object. can instantiate a new Dog object by typing the name of the class,
followed by opening and closing parentheses:
>>> Dog()
<__main__.Dog object at 0x106702d30>
now have a new Dog object at 0x106702d30. This funny-looking string of letters and numbers is
a memory address that indicates where the Dog b ec ed c e e .
Note that the address you see on your screen will be different.
Now instantiate a second Dog object:
>>> Dog()
<__main__.Dog object at 0x0004ccc90>
>>> a = Dog()
>>> b = Dog()
>>> a == b
False
In this code, create two new Dog objects and assign them to the variables a and b. When you
compare a and b using the == operator, the result is False. Even though a and b are both
instances of the Dog class, they represent two distinct objects in memory.
Page 119
PYTHON PROGRAMMING KG College of Arts and Science
from, including name, age, c a c , a d b eed. T ee g e, e e a ea d
age.
The properties that all Dog objects must have are defined in a method called .__init__().
Every time a new Dog object is created, .__init__() sets the initial state of the object by
a g g e a e f e b ec e e. T a , .__init__() initializes each new
instance of the class.
Can give .__init__() any number of parameters, but the first parameter will always be
a variable called self. When a new class instance is created, the instance is automatically passed
to the self parameter in .__init__() so that new attributes can be defined on the object.
Le da e e Dog class with an .__init__() method that creates .name and .age attributes:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
class Dog:
# Class attribute
species = "Canis familiaris"
Class attributes are defined directly beneath the first line of the class name and are indented by
four spaces. They must always be assigned an initial value. When an instance of the class is
created, class attributes are automatically created and assigned to their initial values.
Use class attributes to define properties that should have the same value for every class instance.
Use instance attributes for properties that vary from one instance to another.
Now in Dog c a , e c ea e ed g !
To instantiate objects of this Dog class, need to provide values for the name and age. If d ,
then Python raises a TypeError:
>>> Dog()
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
Dog()
TypeError: __init__() missing 2 required positional arguments: 'name' and 'age'
To pass arguments to the name and age parameters, put values into the parentheses after the class
name:
>>> buddy = Dog("Buddy", 9)
>>> miles = Dog("Miles", 4)
This creates two new Dog instances one for a nine-year-old dog named Buddy and one for a
four-year-old dog named Miles.
The Dog c a .__init__() method has three parameters, so why are only two arguments
passed to it in the example?
When instantiate a Dog object, Python creates a new instance and passes it to the first parameter
of .__init__(). This essentially removes the self-parameter, so need to worry about
the name and age parameters.
After create the Dog instances, can access their instance attributes using dot notation:
>>> buddy.name
'Buddy'
>>> buddy.age
9
>>> miles.name
'Miles'
>>> miles.age
4
can access class attributes the same way:
>>> buddy.species
'Canis familiaris'
One of the biggest advantages of using classes to organize data is that instances are guaranteed
to have the attributes you expect. All Dog instances have .species, .name, and .age attributes,
so can use those attributes with confidence knowing that they will always return a value.
Although the attributes are guaranteed to exist, their values can be changed dynamically:
>>> buddy.age = 10
>>> buddy.age
10
Page 121
PYTHON PROGRAMMING KG College of Arts and Science
In this example, change the .age attribute of the buddy object to 10. Then change
the .species attribute of the miles object to "Felis silvestris", which is a species of cat.
That makes Miles a pretty strange dog, but it is valid Python!
The key takeaway here is that custom objects are mutable by default. An object is mutable if it
can be altered dynamically. For example, lists and dictionaries are mutable, but strings and
tuples are immutable.
class Shark:
animal_type = "fish"
new_shark = Shark()
print(new_shark.animal_type)
Output
fish
program returns the value of the variable.
Add a few more class variables and print them out
#shark.py
class Shark:
animal_type = "fish"
location = "ocean"
followers = 5
new_shark = Shark()
print(new_shark.animal_type)
print(new_shark.location)
print(new_shark.followers)
Page 122
PYTHON PROGRAMMING KG College of Arts and Science
Just like with any other variable, class variables can consist of any data type available to us in
P .I ga a e g a da ege . Le e g a aga e python
shark.py command and review the output:
Output
fish
ocean
5
The instance of new_shark is able to access all the class variables and print them out when run
the program.
Class variables allow us to define variables upon constructing the class. These variables and their
associated values are then accessible to each instance of the class.
5.3.1 INSTANCE VARIABLES
Instance variables are owned by instances of the class. This means that for each object or
instance of a class, the instance variables are different. Unlike class variables, instance variables
are defined within methods.
In the Shark class example below, name and age are instance variables:
class Shark:
def __init__(self, name, age):
self.name = name
self.age = age
When create a Shark object, we will have to define these variables, which are passed as
parameters within the constructor method or another method.
class Shark:
def __init__(self, name, age):
self.name = name
self.age = age
new_shark = Shark("Sammy", 5)
new_shark = Shark("Sammy", 5)
print(new_shark.name)
print(new_shark.age)
When run the program above with python shark.py, receive the following output:
Output
Sammy
5
The output received is made up of the values of the variables that we initialized for the object
instance of new_shark.
Le c ea e a e b ec f e Shark class called stevie:
#shark.py
class Shark:
def __init__(self, name, age):
Page 123
PYTHON PROGRAMMING KG College of Arts and Science
self.name = name
self.age = age
new_shark = Shark("Sammy", 5)
print(new_shark.name)
print(new_shark.age)
stevie = Shark("Stevie", 8)
print(stevie.name)
print(stevie.age)
Output
Sammy
5
Stevie
8
The stevie object, like the new_shark object passes the parameters specific for that instance of the Shark
class to assign values to the instance variables.
Instance variables, owned by objects of the class, allow for each object or instance to have different
values assigned to those variables.
# Class variables
animal_type = "fish"
location = "ocean"
def main():
# First object, set up instance variables of constructor method
sammy = Shark("Sammy", 5)
# Second object
stevie = Shark("Stevie", 8)
if __name__ == "__main__":
main()
When run the program with python shark.py, receive the following output:
Output
Sammy
ocean
Stevie
This user has 77 followers
fish
Here, it is made use of both class and instance variables in two objects of
the Shark class, sammy and stevie.
# Instance method
def description(self):
return f"{self.name} is {self.age} years old"
Page 125
PYTHON PROGRAMMING KG College of Arts and Science
Save the modified Dog class to a file called dog.py and press F5 to run the program. Then open
the interactive window and type the following to see your instance methods in action:
>>>
>>> miles = Dog("Miles", 4)
>>> miles.description()
'Miles is 4 years old'
In the above Dog class, .description() returns a string containing information about
the Dog instance miles. When writing e ca e , a g d dea a ea e d a
returns a string containing useful information about an instance of the class.
However, .description() e Pythonic way of doing this.
When a list object is created , can use print() to display a string that looks like the list:
>>>
>>> names = ["Fletcher", "David", "Dan"]
>>> print(names)
['Fletcher', 'David', 'Dan']
Le see what happens when you print() the miles object:
>>>
>>> print(miles)
<__main__.Dog object at 0x00aeff70>
On use of print(miles),get a cryptic looking message telling that miles is a Dog object at the
memory address 0x00aeff70. T e age e helpful. Can change what gets printed by
defining a special instance method called .__str__().
In the editor window, change the name of the Dog c a .description() method
to .__str__():
class Dog:
# Leave other parts of Dog class as-is
# Replace .description() with __str__()
def __str__(self):
return f"{self.name} is {self.age} years old"
Save the file and press F5 . Now, when you print(miles), you get a much friendlier output:
Page 126
PYTHON PROGRAMMING KG College of Arts and Science
Inheritance is the process by which one class takes on the attributes and methods of another.
Newly formed classes are called child classes, and the classes that child classes are derived from
are called parent classes.
Child classes can override or extend the attributes and methods of parent classes. In other words,
c dca e e a f e ae a b e a d e d b ca a ec f a b e a d
methods that are unique to themselves.
Parent Classes vs Child Classes :
Le c ea e a c d c a f eac f e ee b eed e ed ab e: Jack Russell Terrier,
Dac d, a d B d g. F efe e ce, e e e f def f e Dog class:
class Dog:
species = "Canis familiaris"
def __str__(self):
return f"{self.name} is {self.age} years old"
Remember, to create a child class, you create new class with its own name and then put the name
of the parent class in parentheses. Add the following to the dog.py file to create three new child
classes of the Dog class:
class JackRussellTerrier(Dog):
pass
class Dachshund(Dog):
pass
class Bulldog(Dog):
pass
Press F5 to save and run the file. With the child classes defined, can now instantiate some dogs
of specific breeds in the interactive window:
>>>
>>> miles = JackRussellTerrier("Miles", 4)
>>> buddy = Dachshund("Buddy", 9)
>>> jack = Bulldog("Jack", 3)
>>> jim = Bulldog("Jim", 5)
Instances of child classes inherit all of the attributes and methods of the parent class:
>>>
>>> miles.species
'Canis familiaris'
>>> buddy.name
'Buddy'
Page 127
PYTHON PROGRAMMING KG College of Arts and Science
>>> print(jack)
Jack is 3 years old
>>> jim.speak("Woof")
'Jim says Woof'
To determine which class a given object belongs to, you can use the built-in type():
>>>
>>> type(miles)
<class '__main__.JackRussellTerrier'>
What if you want to determine if miles is also an instance of the Dog class? You can do this with
the built-in isinstance():
>>>
>>> isinstance(miles, Dog)
True
Notice that isinstance() takes two arguments, an object and a class. In the example
above, isinstance() checks if miles is an instance of the Dog class and returns True.
The miles, buddy, jack, and jim objects are all Dog instances, but miles is not
a Bulldog instance, and jack is not a Dachshund instance:
>>>
>>> isinstance(miles, Bulldog)
False
More generally, all objects created from a child class are instances of the parent class, although
they may not be instances of other child classes.
N a c ea ed c d c a e f e d ffe e b eed f d g , e g e eac b eed
sound.
5.6 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 reusab f a c de. We d a e e e a e c de aga a d aga .
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.
Example: Inheritance in Python
# Python code to demonstrate how parent constructors are called parent class
class Person(object):
# __init__ is known as the constructor
def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("My name is {}".format(self.name))
Page 128
PYTHON PROGRAMMING KG College of Arts and Science
print("IdNumber: {}".format(self.idnumber))
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
# invoking the __init__ of the parent class
Person.__init__(self, name, idnumber)
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))
Just like a parent-child relationship, inheritance works on derived classes relative to the base
ca .E e De ed c a e f a Ba e c a . T e e a ce e e e ed UML
or Unified Modeling Language. It is a standard modeling language that includes an integrated set
of diagrams to help developers specify, structure, and document software systems elements.
Inheritance relationship defines the classes that inherit from other classes as derived, subclass, or
sub-type classes. Base class remains to be the source from which a subclass inherits. For
e a e, a e a Ba e c a f A a, a da L a De ed c a . T e e a ce
will be Lion is an Animal.
So, the question is, what does the “Lion” class inherit from “Animal”?
A L ca e
Page 129
PYTHON PROGRAMMING KG College of Arts and Science
Interface
Execution
Advantages of Inheritance in Python
Inheritance in Python helps developers to reuse the objects.
Eac eaca e e ba e c a , ge acce e ae b ec
functionality.
Reusability due to inheritance is also reliable as the base class is already
tested.
Low development time and cost
Standardization of the interface across classes becomes easy.
Reduces redundancy of code and help improve extensibility
The creation of class libraries becomes easy.
1. SINGLE INHERITANCE
Single inheritance is- e e a ce f e De ed c a f e Ba e c a . Le
understand it through an example,
class Country:
def ShowCountry(self):
( T S a );
class State(Country):
def ShowState(self):
( T S a e );
st =State();
st.ShowCountry();
st.ShowState();
2.MULTI-LEVEL INHERITANCE
Page 130
PYTHON PROGRAMMING KG College of Arts and Science
Python is made of several objects, and with the multi-level inheritance, there are endless
possibilities of reusing the class functionalities. Multi-level inheritance gets documented each
time a derived class inherits another derived class. There is no limit to the number of derived
classes that can inherit the functionalities, and that is why multilevel inheritance helps to
improve the reusability in Python.
Page 131
PYTHON PROGRAMMING KG College of Arts and Science
3. MULTIPLE INHERITANCE:
Python enables developers to inherit multiple functionalities and properties from different base
classes into a single derived class. It is mostly a great feature as it can allow you to inherit
multiple dependencies without extensive tools or coding.
4.HIERARCHICAL INHERITANCE
Hierarchical inheritance involves multiple inheritance from the same base or parent class.
Page 132
PYTHON PROGRAMMING KG College of Arts and Science
ob = Child()
ob1 = Child2()
ob.func1()
ob.func2()
5.HYBRID INHERITANCE
Hybrid inheritance involves multiple inheritance taking place in a single program.
class Parent:
def func1(self):
print("this is function one")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child1(Parent):
def func3(self):
print(" this is function 3"):
ob = Child3()
ob.func1()
Page 133
PYTHON PROGRAMMING KG College of Arts and Science
Creating a Worker base class for all the worker types in the company makes the hierarchy easy
for the HR system. Every worker is assigned a name and id. The HR system requires the worker
to provide data regarding their weekly salary through the .calculate_payroll() interface. The
execution of this interface may differ according to the type of worker.
i)Constructor :
Constructor is a type of subroutine in object-oriented programming. Constructor is used to
assigning value to data members when an object is created inside a class. The __init__()
function is used as a constructor in python almost every time create an object. In
polymorphism, this __init__() function is used almost everywhere.
Page 135
PYTHON PROGRAMMING KG College of Arts and Science
What is polymorphism in Python?
Polymorphism in Python is used for a common function name that can be used for different
types. This concept is widely applied in object-oriented based Python programming. Like
other programming languages say Java, C+, polymorphism is also implemented in python for
different purpose commonly Duck Typing, Operator overloading and Method overloading,
and Method overriding. This polymorphism process can be achieved in two main ways
namely overloading and overriding.
#Example 2
>>> 4 + 5
45
#Example 3
>>> ab + cd
abcd
In the above example can clearly see that the addition operator is used in different way.
In the first example the as the data sent are two integer values, the operator did the addition
operation of two numbers.
And in the second example, as the same values are sent as data in the form of string, and the
same operator did the concatenation (concatenation is the process by which two strings ar e
joined end-to-end) of the two strings.
In the third example, the data sent are two strings but the operator is same as the above and
it did the concatenation of the two strings.
>>> 3 + ab
3ab
In this example the addition operator did the concatenation of the two strings though the first
value is a integer but here in this specific example it is sent as strings.
So these were the few basic examples of polymorphism in python.
>>>print(2*7)
14
>>> ( a *3)
aaa
Page 136
PYTHON PROGRAMMING KG College of Arts and Science
So in the above example the multiplication operator did the multiplication of two numbers in
the first one, but in the second one as the multiplication of a string and an integer is not
possible so the character is printed repeatedly for 3 times. So it shows how a single operator
can be used in different way.
class Vehicle:
def __init__(self, fare):
self.fare = fare
def __add__(self, other)://using the special function __add__ operator
return self.fare+ other.fare
bus= Vehicle(20)
car= Vehicle(30)
total_fare=bus+ car
print(total_fare)
#Output:
50
Overloading the special function magically defines everytime plus operator is used in the
object total_fare=bus+ car . User is going to add their fares
#Example 2: Let us compare the fares of different vehicles in this example
class Vehicle:
def __init__(self, fare):
self.fare = fare
def __lt__(self, other):// relational operator __lt__ is used here as the special function
return self.fare< other.fare
bus= Vehicle(10)
car= Vehicle(30)
compare=bus< car
print(compare)
Output:
True
__lt__ It is the relational operator which is used as a special function for operator
overloading in the above example.
ii)Method Overloading
Method overloading means a class containing multiple methods with the same name but
may have different arguments. Basically python does not support method overloading, but
there are several ways to achieve method overloading. Though method overloading can be
achieved, the last defined methods can only be usable.
Le ake an e am le fo be e nde anding
Le c de a c a A, eca a e a e af c c a ac c or
self and arguments whose default values assigned are None and None. User created an object
a d ca ed e f c e b ec b . ,b dd a a ag e g
print None and None cause in the function part assigned the default values.
Example:
Page 137
PYTHON PROGRAMMING KG College of Arts and Science
class A:
def show(self, a=None, b=None):
print(a,b)
obj=A()
obj.show()
Output
None None
Now to pass any other value then that need to call another function obj.show() with an
argument in it.
Example:
class A:
def show(self, a=None, b=None):
print(a,b)
obj=A()
obj.show()
obj.show(4)
Output
None None
4 None
Here in the output the None value assigned for a in the function part is replaced with 4. In
the function call part 4 is passed as the argument.
Now two argument is passed during the function call see what will happen in the next
example,
#Example:
class A:
def show(self, a=None, b=None):
print(a,b)
obj=A()
obj.show()
obj.show(4)
obj.show(4,5)
Output
None None
4
45
Here as two arguments 4 and 5 are passed during function call two different values are
assigned for a and b.So in the above example the same method and use different f unction
calls in different ways is seen
B)METHOD OVERRIDING :
Method overriding is the process of modifying a base class from the derived class having the
same methods and same number of arguments. Le a e a e a e a d ee
works. First of all create a base class with a method and then create a derived class without
any method,
#Example:
class Vehicle:
def run(self):
print("Saves Energy")
class EV(Vehicle):
pass
ev = EV()
Page 138
PYTHON PROGRAMMING KG College of Arts and Science
ev.run()
S e ef c ca ed, e e ba e c a e d, a e de ed
class has no method in it.
Output:
Saves Energy
Now in the next example declare another method under the derived class with the same
a e a ba e c a b a d ffe e a g e . A e ba e c a e d
e dde b e de ed c a , e de ed c a e d be ed a e .
#Example:
class Vehicle:
def run(self):
print("Saves Energy")
class EV(Vehicle):
def run(self):
print("Run on Electricity")
ev = EV()
ev.run()
Output
Run on Electricity
Duck Typing
Duck typing is a concept in polymorphism. The term duck typing is derived from the quote
which says something that walks like a duck quacks like a duck and swims like a duck is
called a duck no matter what object it is. In simple words it means something that matches
its behaviour to anything then it will consider a thing of that category to which it matches.
When Talking about object-oriented programming in python the term polymorphism will
come for sure. In object-oriented programming, objects need to take different forms. In
s f a e de e e , e a a e fea e. T g , a
single action can be performed in various ways. This concept is widely used when we talk
about loose coupling, dependency injection and interface etc.
Page 139
PYTHON PROGRAMMING KG College of Arts and Science
Similarly, for string data types, + operator is used to perform concatenation.
str1 = "Python"
str2 = "Programming"
print(str1+" "+str2)
As a result, the above program outputs Python Programming.
Here, a single operator + has been used to carry out different operations for distinct data types.
This is one of the most simple occurrences of polymorphism in Python.
Output
9
3
2
Here, many data types such as string, list, tuple, set, and dictionary can work with
the len() function. However, can see that it returns specific information about specific data
types.
Page 140
PYTHON PROGRAMMING KG College of Arts and Science
Here, we have created two classes Cat and Dog . They share a similar structure and have the
same method names info() and make_sound() .
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")
def make_sound(self):
print("Meow")
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")
def make_sound(self):
print("Bark")
However, notice that it have not created a common superclass or linked the classes together in
any way. Even then, can pack these two different objects into a tuple and iterate through it using
a common animal variable. It is possible due to polymorphism.
Page 141
PYTHON PROGRAMMING KG College of Arts and Science
class EV(Vehicle):
def run(self):
super().run()//super function is used to call the method of base class
print("Run on Electricity")
ev = EV()
ev.run()
Output:
Saves Energy
Run on Electricity
def area(self):
pass
def fact(self):
return "I am a two-dimensional shape."
def __str__(self):
return self.name
class Square(Shape):
def __init__(self, length):
super().__init__("Square")
self.length = length
def area(self):
return self.length**2
def fact(self):
return "Squares have each angle equal to 90 degrees."
class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius
Page 142
PYTHON PROGRAMMING KG College of Arts and Science
def area(self):
return pi*self.radius**2
a = Square(4)
b = Circle(7)
print(b)
print(b.fact())
print(a.fact())
print(b.area())
Output
Circle
I am a two-dimensional shape.
Squares have each angle equal to 90 degrees.
153.93804002589985
Here, can see that the methods such as __str__() , which have not been overridden in the child
classes, are used from the parent class.
Due to polymorphism, the Python interpreter automatically recognizes that the fact() method
for object a (Square class) is overridden. So, it uses the one defined in the child class.
On the other hand, since the fact() method for object b isn't overridden, it is used from the
Parent Shape class.
Page 143
PYTHON PROGRAMMING KG College of Arts and Science
Function overloading T e a g e f e a e be a a a c a
function. The operation performed varies by the types of objects or arguments involved.
Instance variable A a ab e a is defined inside a method and belongs only to the
current instance of a class.
Inheritance T e a fe f e c a ac e c f a ca e ca e a ae
derived from it.
Instance A d d a b ec f a ce a c a . A b ec b a belongs to a class
Circle, for example, is an instance of the class Circle.
Instantiation T e c ea fa a ce f a c a .
Method A ec a d ff c a def ed a c a def .
Object A e a ce f a da a c e at's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
Operator overloading T e a g e f e a e f c a a c a
operator.
Everything in Python is an object and define objects through classes. To define an object,
actually create an instance of a class. Thus, class is the most fundamental piece in Python.
P special methods (called magic methods).
The names of these methods begin and end with double underscores (__).
Suppose t have a simple Word class, and want an equals() method that compares two
words but ignores case.
That is, a Word containing the value 'kg' would be considered equal to one containing 'KG'.
Classes have:
Data attributes: Define what is needed to create an instance of a class
Methods (i.e. procedural attributes): Define how to interact with the instances of a class
Own classes using data and procedural attributes can be created and can implement various
functions to customize a class. In addition to the user-defined functions, it is possible to use built-
in Python function within user-defined classes. This is what special (or magic) methods are for.
Special methods allow for using the built-in Python functions to enrich user-defined classes.
Consider the print function which is one of the most commonly used Python function. To print an
instance of the class, it will print out something like the following:
<__main__.Book object at 0x7f9ed5b1d590>
It displays the name of the class (Book) and the memory location of the object which is not a
proper use of the print function. Can customize its behavior by implementing the __str__ special
method in our class.
#Example
>>> class Word():
def __init__(self, text):
self.text = text
def __eq__(self, word2):
return self.text.lower() == word2.text.lower()
Le ee f :
>>> first = Word('kg')
Page 144
PYTHON PROGRAMMING KG College of Arts and Science
>>> ec d = W d('KG )
>>> third = Word('eh')
>>> first == second
True
>>> first == third
1. __init__
The __init__ special method is automatically executed when an instance of class is created. It is
also called class constructor. The parameters of the __init__ represent the data attributes of a
class.
Le c ea e a c a ca ed B .
self.name = name
self.writer = writer
self.pages = pages
The self refers to the instance itself. The Book class has 3 data attributes that need to be specified
when creating a Book instance.
2. __str__
use the __str__ special method to implement the built-in print function within our class. Without
the __str__, here is what print function does.
print(b)
<__main__.Book object at 0x7f9ed5b1d590>
Le def e e __ __ e d c a def .
def __str__(self):
Now the print function will return the title of the name. It accesses the name of the book through
the name attribute. can customize it in any way
print(b)
The title of the book is Moby Dick
3. __len__
Page 145
PYTHON PROGRAMMING KG College of Arts and Science
The len function returns the length of an object. For strings, it returns the number of characters.
For a Pandas data frame, it returns the number of row. Can customize its behavior by
e e g e __ e __ ec a e d c a def . Le a e e e
number of pages of a book object.
If the __len__ is not implemented in the class definition, you will get an error if you try to use
it on an object of your class. It does not have a default behavior like the print function.
def __len__(self):
return int(self.pages)
len(b)
378
Please note that each time a new function is added to the class, need to recreate the object to be
able to use the new functions.
4. __eq__
The __eq__ special method allows for comparing two instances of a class. If it is defined in the
class, can check if an instance is equal to another instance. The equality condition is specified
using the __eq__ method.
In this case, can declare two books being equal if the names and writers of the book are the
same. They might have different number of pages.
T e == ea e T e fb a e a d e ae e a ef a ce . Le
create two books and check if they are equal.
Table SP. lists special methods that objects must implement to emulate numbers. Mathematical
operations are always evaluated from left to right; when an expression such as x + y appears,
the interpreter tries to invoke the method x.__add__(y). The special methods beginning with r
ea e e ed e a d . T e e a e ed f e ef ea dd e
implement the specified operation. For example, if x in x + y doe
the __add__() method, the interpreter tries to invoke the method y.__radd__(x).
The methods __iadd__(), __isub__(), and so forth are used to support in-place arithmetic
operators such as a+=b and a-=b (also known as augmented assignment). A distinction is made
between these operators and the standard arithmetic methods because the implementation of the
in-place operators might be able to provide certain customizations such as performance
optimizations. For instance, if the self parameter is not shared, it might be possible to modify its
value in place without having to allocate a newly created object for the result.
By using the above special methods or magic methods or dunder methods can be utilised
efficiently for classes or for programming.
Page 148
PYTHON PROGRAMMING KG College of Arts and Science
Parameters
object: The type() returns the type of this object if one parameter is specified.
bases (optional): It specifies the base classes.
dict (optional): It specifies the namespace with the definition for the class.
Return
It returns the type of the specified object if a single argument is passed to the type(). If three
arguments are passed, it returns a new type of object.
class Python:
a=0
InstanceOfPython = Python()
print(type(InstanceOfPython))
Output:
<class 'list'>
<class 'dict'>
<class '__main__.Python'>
Explanation: In the above example, we have taken a List that contains some values, and in
return, it prints the type of the List.
In the second case, we have taken a Dict that contains some values, and in return, it prints the
type of the Dict.
Then, defined a class named as Python and produced an InstanceOfPython which prints its type.
print(result)
type() Syntax
The type() function has two different forms:
# type with single parameter
Page 149
PYTHON PROGRAMMING KG College of Arts and Science
type(object)
# type with 3 parameters
type(name, bases, dict)
type() Parameters
The type() function either takes a single object parameter.
Or, it takes 3 parameters
name - a class name; becomes the __name__ attribute
bases - a tuple that itemizes the base class; becomes the __bases__ attribute
dict - a dictionary which is the namespace containing definitions for the class body;
becomes the __dict__ attribute
type() Return Value
The type() function returns type of the object, if only one object parameter is passed a new
type, if 3 parameters passed
Example 1: type() with Object parameter
numbers_list = [1, 2]
print(type(numbers_list))
class test:
a = 'Foo'
b = 12
Page 150
PYTHON PROGRAMMING KG College of Arts and Science
In the program, have used the Python vars() function which returns
the __dict__ attribute. __dict__ is used to store object's writable attributes. can easily change
these attributes if necessary. For example, to change the __name__ attribute of o1 to 'Z' , use:
o1.__name = 'Z'
ANOTHER EXAMPLE :
# Python3 code to explain the type() function Class of type dict
class DictType:
DictNumber = {1:'John', 2:'Wick', 3:'Barry', 4:'Allen'}
# Will print accordingly whether both the objects are of same type or not
if type(d) is not type(l):
print("Both class have different object type.")
else:
print("Same Object type")
Remember, if you remove +sign from the w+, the output will change, and it will only give the
first character of the first letter, i.e., [g]
iii)re.findall()
findall() d e ed ea c f a cc e ce a match a given pattern. In contrast,
search() module will only return the first occurrence that matches the specified pattern. findall()
will iterate over all the lines of the file and will return all non-overlapping matches of pattern in
a single step.
For example, here we have a list of e-mail addresses, and we want all the e-mail addresses to be
fetched out from the list, we use the method re.findall() in Python. It will find all the e-mail
addresses from the list.
import re
5.13.CHARACTER CLASS
A "character class", or a "character set", is a set of characters put in square brackets. The
regex engine matches only one out of several characters in the character class or character set.
Place the characters where it is needed to match between square brackets. To match any vowel,
use the character set [aeiou]. A character class or set matches only a single character. The order
of the characters inside a character class or set does not matter. The results are identical. use a
hyphen inside a character class to specify a range of characters. [0-9] matches a single digit
between 0 and 9. Similarly for uppercase and lowercase letters we have the character class [A-
Za-z]
#Example
The following code finds and prints all the vowels in the given string
import re
s = 'mother of all battles'
result = re.findall(r'[aeiou]', s)
print result
Output
This gives the output
['o', 'e', 'o', 'a', 'a', 'e']
Page 154
PYTHON PROGRAMMING KG College of Arts and Science
range unless it's the first character, in which case it's a literal hyphen. Since some sets of
characters are required so frequently, several have shorthand forms, which are shown in Table 1.
With one exception, the shorthands can be used inside character sets; for example, the
regex [\dA-Fa-f] matches any hexadecimal digit. The exception is the period (.) which is a
shorthand outside a character class but matches a literal period inside a character class.
Table 1 Character Class Shorthands
Symbol Meaning
. Matches any character except newline, any character at all with the re.DOTALL flag, or
inside a character class matches a literal period.
\d Matches a Unicode digit, or [0-9] with the re.ASCII flag.
\D Matches a Unicode nondigit, or [^0-9] with the re.ASCII flag.
\s Matches a Unicode whitespace, or [ \t\n\r\f\v] with the re.ASCII flag.
\S Matches a Unicode non-whitespace, or [^ \t\n\r\f\v] with the re.ASCII flag.
\w Matches a Unicode "word" character, or [a-zA-Z0-9_] with the re.ASCII flag.
\W Matches a Unicode non-"word" character, or [^a-zA-Z0-9_] with the re.ASCII flag.
Quantifiers specify how many instances of a character, group, or character class must be
present in the input for a match to be found. A quantifier has the form {m,n} where m and n are
the minimum and maximum times the expression to which the quantifier applies must match.
For example, both e{1,1}e{1,1} and e{2,2} match feel, but neither matches felt. Writing a
quantifier after every expression would soon become tedious, and is certainly difficult to read.
Regex language supports several convenient shorthands. If only one number is given in
the quantifier, it's taken to be both the minimum and the maximum, so e{2} is the same
as e{2,2}. As noted in the preceding section, if no quantifier is explicitly given, it's assumed to
be 1 (that is, {1,1} or {1}); therefore, ee is the same as e{1,1}e{1,1} and e{1}e{1}, so
both e{2} and ee match feel but not felt.
Having a different minimum and maximum is often convenient. For example, to
match travelled and traveled (both legitimate spellings),we could use
either travel{1,2}ed or travell{0,1}ed. The {0,1} quantification is used so often that it has its
own shorthand form, ?, so another way of writing the regex (and the one most likely to be used
in practice) is travell?ed.
Two other quantification shorthands are provided: A plus sign (+) stands for {1,n} ("at least
one") and an asterisk (*) stands for {0,n} ("any number of"). In both cases, n is the maximum
possible number allowed for a quantifier, usually at least 32767. Table 2 shows all the
quantifiers.
The + quantifier is very useful. For example, to match integers, could use \d+ to match one or
more digits. This regex could match in two places in the string 4588.91, for
example: 4588.91 and 4588.91. Sometimes typos are the result of pressing a key too long. We
could use the regex bevel+ed to match the legitimate beveled and bevelled, and the
incorrect bevellled. If we wanted to standardize on the single-l spelling, and match only oc
Table 2 Regular Expression Quantifiers
Syntax Meaning
e? or e{0,1} Greedily match zero occurrences or one occurrence of expression e.
e?? or e{0,1}? Nongreedily match zero occurrences or one occurrence of expression e.
e+ or e{1,} Greedily match one or more occurrences of expression e.
e+? or e{1,}? Nongreedily match one or more occurrences of expression e.
e* or e{0,} Greedily match zero or more occurrences of expression e.
e*? or e{0,}? Nongreedily match zero or more occurrences of expression e.
e{m} Match exactly m occurrences of expression e.
Page 155
PYTHON PROGRAMMING KG College of Arts and Science
e{m,} Greedily match at least m occurrences of expression e.
e{m,}? Nongreedily match at least m occurrences of expression e.
e{,n} Greedily match at most n occurrences of expression e.
e{,n}? Nongreedily match at most n occurrences of expression e.
e{m,n} Greedily match at least m and at most n occurrences of expression e.
e{m,n}? Nongreedily match at least m and at most n occurrences of expression e.
The + symbol used after the \d in the example above is used for repetition. You will see this in
some more detail in the repetition section later on...
Page 156
PYTHON PROGRAMMING KG College of Arts and Science
\r - Lowercase r. Matches return.
\A - Uppercase a. Matches only at the start of the string. Works across multiple lines as well.
\Z - Uppercase z. Matches only at the end of the string.
TIP: ^ and \A are effectively the same, and so are $ and \Z. Except when dealing with
Let's understand this concept with a simple example. Imagine you were validating email
addresses and wanted to check the user name and host. This is when you would want to create
separate groups within your matched text.
Another way of doing the same is with the usage of <> brackets instead. This will let you create
named groups. Named groups will make your code more readable. The syntax for creating
named group is: (?P<name>...). Replace the name part with the name you want to give to your
group. The ... represent the rest of the matching syntax. See this in action using the same
example as before...
In all cases, a shorter match would also be valid. But as the regex engine is greedy per default,
those are not enough for the regex engine.
5.21 GROUPING
Example Print the part of the string where there was a match. The regular expression looks for
any words that starts with an upper case "S":
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group())
#Output:
Spain
The search() Function The search() function searches the string for a match, and returns a
Match object if there is a match. If there is more than one match, only the first occurrence of the
match will be returned: Example txt = "The rain in Spain" x = re.search("\s", txt) print("The first
white-space character is located in position:", x.start())
Page 158
PYTHON PROGRAMMING KG College of Arts and Science
5.22 GREEDY VS. NON-GREEDY MATCHING :
When a special character matches as much of the search sequence (string) as possible, it is said
to be a "Greedy Match". It is the normal behavior of a regular expression, but sometimes this
behavior is not desired:
pattern = "cookie"
sequence = "Cake and cookie"
heading = r'<h1>TITLE</h1>'
re.match(r'<.*>', heading).group()
'<h1>TITLE</h1>'
The pattern <.*> matched the whole string, right up to the second occurrence of >.
However, if you only wanted to match the first <h1> tag, you could have used the greedy
qualifier *? that matches as little text as possible.
Adding ? after the qualifier makes it perform the match in a non-greedy or minimal fashion; That
is, as few characters as possible will be matched. When you run <.*>, you will only get a match
with <h1>.
heading = r'<h1>TITLE</h1>'
re.match(r'<.*?>', heading).group()
'<h1>'
import re
txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)
#o/p
['The', 'rain', 'in', 'Spain']
5.24 SUBSTITUTING
The sub() function replaces the matches with the text of your choice:
#Example Replace every white-space character with the number 9:
import re
txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x)
o/p
The9rain9in9Spain
#Example
import re
#Replace the first two occurrences of a white-space character with the digit 9:
txt = "The rain in Spain"
x = re.sub("\s", "9", txt, 2)
print(x)
#output
Page 159
PYTHON PROGRAMMING KG College of Arts and Science
The9rain9in Spain
It is a lot of information and concepts to grasp! The following table summarizes all
Page 160