Python OOP Concepts and Class Creation
Python OOP Concepts and Class Creation
2. Creating Class:
A class is a collection of objects or you can say it is a blueprint of objects defining the
common attributes and behavior.
A class is a virtual entity and can be seen as a blueprint of an object. The class came into
existence when it instantiated.
1 [Link],CSD dept,Aitam
Python Programming UNIT-V
A class contains the properties (attribute) and action (behavior) of the object. Properties
represent variables, and the methods represent actions. Hence class includes both
variables and methods.
On the other hand, the object is the instance of a class. The process of creating an object
can be called instantiation.
As class is collection of attributes and methods.
Example:
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.
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.
Attributes are the variables that belong to a class.
Attributes are always public and can be accessed using the dot (.) operator.
The Class is defined under a “Class” Keyword
The syntax of the Class Definition is:
class ClassName:
# Statement-1
# Statement-N
2 [Link],CSD dept,Aitam
Python Programming UNIT-V
Example Example
x =5 def details(self):
class definitions cannot be empty, but for some reason if you have a class definition with
no content, put in the pass statement to avoid getting an error.
Example
class Person:
pass
3. Creating Object:
When an object of a class is created, the class is said to be instantiated.
All the instances share the attributes and the behavior of the class.
A single class may have any number of instances.
A class needs to be instantiated if we want to use the class attributes in another class or
method.
A class can be instantiated by calling the class using the class name.
The class object could be used to access different attributes.
Attributes may be data or method. Methods of an object are corresponding functions of
that class.
The syntax to create the instance of the class is given below:
3 [Link],CSD dept,Aitam
Python Programming UNIT-V
Syntax
object-name = class-name(arguments)
Example
class MyClass:
x =5
p1=MyClass()
print(p1.x)
[Link]()
4. Constructor in Python:
Syntax
4 [Link],CSD dept,Aitam
Python Programming UNIT-V
Here,
self : The first argument self refers to the current object. It binds the instance to
the init () method. It’s usually named self to follow the naming convention.
Example
class Person:
[Link] = name
[Link] = age
p1 = Person("John", 36)
print([Link])
print([Link])
class employee():
[Link] = name
[Link] = age
[Link] = salary
emp1 = employee("Hemanth",22,1234)
5 [Link],CSD dept,Aitam
Python Programming UNIT-V
class Book:
[Link] = title
[Link] = author
[Link] = price
print(b1)
print(b2)
Output:
b1, b2 are distinct objects of the class Book. The term self in the attributes refers to the
corresponding instances (objects).
The class and memory location of the objects are printed when they are printed.
We can't expect them to provide specific information such as the title, author name, and
so on.
But we can use a specific method called repr to do this.
In Python, a special method is a defined function that starts and ends with two
underscores and is invoked automatically when certain conditions are met.
6 [Link],CSD dept,Aitam
Python Programming UNIT-V
class Book:
[Link] = title
[Link] = author
[Link] = price
print(b1)
print(b2)
Output
5. The self-parameter:
The self-parameter refers to the current instance or current object of the class and
accesses the class variables.
We can use anything instead of self, but it must be the first parameter of any function
which belongs to the class.
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.
7 [Link],CSD dept,Aitam
Python Programming UNIT-V
If we have a method that takes no arguments, then we still have to have one argument i.e.
self.
Python class variables are declared within a class and their values are the same across all
instances of a class.
Python instance variables can have different values across multiple instances of a class.
Class variables share the same value among all instances of the class. The value of
instance variables can differ across each instance of a class.
Instance variables are for data, unique to each instance and class variables are for
attributes and methods shared by all instances of the class.
Instance variables are variables whose value is assigned inside a constructor or method
with “self” whereas class variables are variables whose value is assigned in the class.
class variables are variables whose value is assigned in the class.
[Link] = name
print([Link]) print([Link])
obj2 = Shark("Stevie")
print([Link])
Output Output
Fish Sammy
Stevie
8 [Link],CSD dept,Aitam
Python Programming UNIT-V
7. Python 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.
Inheritance is the ability to ‘inherit’ features or attributes from already written classes
into newer classes we make.
Inheritance provides code reusability to the program because we can use an existing class
to create a new class instead of creating it from scratch.
i. Single Inheritance:
Single Inheritance is the simplest form of inheritance where a single child class or
derived class is derived from a single parent class.
Syntax
<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>
9 [Link],CSD dept,Aitam
Python Programming UNIT-V
Example Output
class Animal: dog barking
def speak(self): Animal Speaking
print("Animal Speaking")
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
[Link]()
[Link]()
def info(self):
print([Link], [Link], [Link])
10 [Link],CSD dept,Aitam
Python Programming UNIT-V
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:
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
Example Output
11 [Link],CSD dept,Aitam
Python Programming UNIT-V
Example Output
Hello Parent1
class parent1:
def func1: Hello Parent2
print(“Hello Parent1”)
Hello Child
class parent2
def func2:
print(“Hello Parent2”)
class child(parent1, parent2):
def func3:
print(“Hello Child”)
t=child()
t.func1()
t.func2()
t.func3()
Python provides us the flexibility to inherit multiple base classes in the child class.
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
12 [Link],CSD dept,Aitam
Python Programming UNIT-V
Example Output
class Cal_1: 30
def Sum(self,a,b): 200
return a+b 0.5
class Cal_2:
def Mul(self,a,b):
return a*b
class Derived(Cal_1,Cal_2):
def Div(self,a,b):
return a/b
d = Derived()
print([Link](10,20))
print([Link](10,20))
print([Link](10,20))
i. Modular Codebase: Increases modularity i.e. breaking down codebase into modules
which makes it easier to understand. Here, each class that we define becomes a separate
module that can be separately inherited by one or many classes.
ii. Code Reusability: the child class copies all the attributes and methods of the parent class
into its own class and use. This saves time and coding effort by not rewriting them thus
following modularity paradigms.
iii. Less Development: and Maintenance Costs: changes just need to be made in the base
class, all derived classes will automatically follow.
i. Decreases the Execution Speed: loading multiple classes because they are
interdependent on each other
13 [Link],CSD dept,Aitam
Python Programming UNIT-V
ii. Tightly Coupled Classes: this means that even though parent classes can be executed
independently, child classes cannot be executed without defining their parent classes.
Example
^a...s$
The above code defines a RegEx pattern. The pattern is: any five letter string starting
with a and ending with s.
A pattern defined using RegEx can be used to match against a string.
14 [Link],CSD dept,Aitam
Python Programming UNIT-V
Syntax
import re
2. MetaCharacters:
Meta characters are characters that are interpreted in a special way by a RegEx engine.
Here's a list of meta characters:
[] . ^ $ * + ? {} () \ |
i. Square brackets( [ ] ):
Here, [abc] will match if the string you are trying to match contains any of the a, b or c.
You can also specify a range of characters using - inside square brackets.
[a-e] is the same as [abcde].
[1-4] is the same as [1234].
[0-39] is the same as [01239].
You can complement (invert) the character set by using caret ^ symbol at the start of a
square-bracket.
[^abc] means any character except a or b or c.
[^0-9] means any non-digit character.
15 [Link],CSD dept,Aitam
Python Programming UNIT-V
ii . Period (..) :
A period matches any single character (except newline '\n').
Expression String Matched?
A No match
..
Ac 1 match
Acd 1 match
Acde 2 matches (contains 4
characters)
iii. Caret(^):
The caret symbol ^ is used to check if a string starts with a certain character.
iv. Dollar($):
The dollar symbol $ is used to check if a string ends with a certain character.
v. Star(*):
The star symbol * matches zero or more occurrences of the pattern left to it.
16 [Link],CSD dept,Aitam
Python Programming UNIT-V
ma*n Mn 1 match
Man 1 match
Maaan 1 match
Main No match ( a is not followed by n )
Woman 1 match
vi. Plus(+):
The plus symbol + matches one or more occurrences of the pattern left to it.
Expression String Matched?
ma+n Mn No match (no a character)
Man 1 match
Maaan 1 match
Main No match (a is not followed by n)
Woman 1 match
vii. Braces( { } ):
Consider this code: {n,m}. This means at least n, and at most m repetitions of the pattern
left to it.
17 [Link],CSD dept,Aitam
Python Programming UNIT-V
Let's try one more example. This RegEx [0-9]{2, 4} matches at least 2 digits but not
more than 4 digits
Expression String Matched?
[0-9]{2,4} ab123csde 1 match (match at ab123csde )
12 and 345673 3 matches (12, 3456 , 73)
1 and 2 No match
ix . Alternation( | ):
Vertical bar | is used for alternation (or operator).
Expression String Matched?
a|b Cde No match
Ade 1 match (match at ade)
acdbea 3 matches (at acdbea)
xi. Backslash(\):
Backlash \ is used to escape various characters including all metacharacters. For
example,
18 [Link],CSD dept,Aitam
Python Programming UNIT-V
a football Match
afootball No match
19 [Link],CSD dept,Aitam
Python Programming UNIT-V
20 [Link],CSD dept,Aitam
Python Programming UNIT-V
Meta characters:
Special Sequences:
A special sequence is a \ followed by one of the characters in the list below, and has a
special meaning:
21 [Link],CSD dept,Aitam
Python Programming UNIT-V
22 [Link],CSD dept,Aitam
Python Programming UNIT-V
4. RegEx Functions:
The re module offers a set of functions that allows us to search a string for a match:
Function Description
split Returns a list where the string has been split at each match
i. findall() Function
Example-1
import re
x = [Link]("ai", txt)
print(x)
Example-2
23 [Link],CSD dept,Aitam
Python Programming UNIT-V
pattern = '\d+'
result = [Link](pattern, string)
print(result)
The list contains the matches in the order they are found.
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.
The [Link]() method takes two arguments: a pattern and a string. The method looks for
the first location where the RegEx pattern produces a match with the string.
If the search is successful, [Link]() returns a match object; if not, it returns None
Example-1
import re
x = [Link]("\s", txt)
24 [Link],CSD dept,Aitam
Python Programming UNIT-V
Example-2
import re
if match:
else:
The split() function returns a list where the string has been split at each match:
Example-1
import re
x = [Link]("\s", txt)
print(x)
25 [Link],CSD dept,Aitam
Python Programming UNIT-V
Example-2
import re
pattern = '\d+'
print(result)
The sub() function replaces the matches with the text of your choice
Example-1
import re
print(x)
Example-2
import re
26 [Link],CSD dept,Aitam
Python Programming UNIT-V
de 23 \n f45 6'
pattern = '\s+'
replace = ''
print(new_string)
Output: abc12de23f456
Match Object
A Match Object is an object containing information about the search and the result.
You can get methods and attributes of a match object using dir() function.
Some of the commonly used methods and attributes of match objects are:
Note: If there is no match, the value None will be returned, instead of the Match Object.
Example
import re
x = [Link]("ai", txt)
print(x)
The Match object has properties and methods used to retrieve information about the
search, and the result:
27 [Link],CSD dept,Aitam
Python Programming UNIT-V
i. span()
It returns a tuple containing the start-, and end positions of the match.
Example
import re
x = [Link](r"\bS\w+", txt)
print([Link]())
ii. string:
Example
import re
x = [Link](r"\bS\w+", txt)
print([Link])
iii. group():
28 [Link],CSD dept,Aitam
Python Programming UNIT-V
Example-1
import re
x = [Link](r"\bS\w+", txt)
print([Link]())
Example-2
import re
string = '39801 356, 2102 1111'
pattern = '(\d{3}) (\d{2})'
match = [Link](pattern, string)
if match:
print([Link]())
else:
print("pattern not found")
Output: 801 35
[Link](), [Link]()
The start() function returns the index of the start of the matched substring.
Similarly, end() returns the end index of the matched substring.
Example
>>> [Link]()
>>> [Link]()
29 [Link],CSD dept,Aitam