0% found this document useful (0 votes)
15 views29 pages

Python OOP Concepts and Class Creation

This document covers Python programming concepts, focusing on object-oriented principles such as classes, objects, inheritance, and regular expressions. It explains how to create classes and objects, the use of constructors, instance and class variables, and the advantages and disadvantages of inheritance. Additionally, it introduces regular expressions and their application in pattern matching.

Uploaded by

hemavaradi93
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views29 pages

Python OOP Concepts and Class Creation

This document covers Python programming concepts, focusing on object-oriented principles such as classes, objects, inheritance, and regular expressions. It explains how to create classes and objects, the use of constructors, instance and class variables, and the advantages and disadvantages of inheritance. Additionally, it introduces regular expressions and their application in pattern matching.

Uploaded by

hemavaradi93
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming UNIT-V

 Classes in Python: Principles of Object Orientation, Creating Classes, Instance Methods


, Special Methods ,class Variables and Inheritance, Data base connectivity .
 Regular Expressions: Introduction, Special Symbols and Characters, Res and Python

1. Principles of object orientation:


i. Classes
ii. Objects
iii. Abstraction
iv. Encapsulation
v. Inheritance
vi. Polymorphism
 Class: OOP in Python is class-based and your objects will be defined with the class
keyword
 Object: Objects purposely represent real-world objects or things like a car or flower.
Python objects have a collection of related properties or behaviors like model() or
colour().
 Abstraction: Abstraction is the concept of hiding all the implementationof your class
away from anything outside of the class.
 Encapsulation: Encapsulation is the method of keeping all the state, variables, and
methods private unless declared to be public.
 Inheritance: Inheritance is the mechanism for creating a child class that can inherit
behavior and properties from a parent(derived) class.
 Polymorphism: Polymorphism is a way of interfacing with objects and receiving
different forms or results.

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

class MyClass: class Book:

x =5 def details(self):

print(“This is python Book”)

2.1 The pass Statement:

 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:

The _init_( ) method:

 The init() method is called the constructor in Python.


 It is a special method that starts and ends with two underscores and is invoked or calls
automatically when object is created for class.
 Constructor is a special method used to create and initialize an object of a class.
 Like methods, a constructor also contains a collection of statements that are executed at
the time of Object creation.
 It runs 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.
 All classes have a function called init (), which is always executed when the class is
being initiated.

Syntax

def init (self):

# body of the constructor

4 [Link],CSD dept,Aitam
Python Programming UNIT-V

Here,

 def : The keyword is used to define function.

 init () : It is a reserved method. This method gets called as soon as an object of a


class is instantiated.

 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:

def init (self, name, age):

[Link] = name

[Link] = age

p1 = Person("John", 36)

print([Link])

print([Link])

class employee():

def init (self,name,age,salary):

[Link] = name

[Link] = age

[Link] = salary

emp1 = employee("Hemanth",22,1234)

emp2 = employee("Sai",23, 2234)

5 [Link],CSD dept,Aitam
Python Programming UNIT-V

class Book:

def init (self, title, author, price):

[Link] = title

[Link] = author

[Link] = price

b1 = Book('Python', 'abc', 120)

b2 = Book('Java', 'xyz', 220)

print(b1)

print(b2)

Output:

< main .Book object at 0x00000156EE59A9D0>

< main .Book object at 0x00000156EE59A8B0>

 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:

def init (self, title, author, price):

[Link] = title

[Link] = author

[Link] = price

def repr (self):

return f"Book: {[Link]}, Author: {[Link]}, Price:{[Link]}"

b1 = Book('Python', 'abc', 120)

b2 = Book('Java', 'xyz', 220)

print(b1)

print(b2)

Output

Book: Python, Author: abc, Price: 120

Book: Java, Author: xyz, Price: 220

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.

6. Instance Variables & class variables:

 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.

class variables Example Instance Variables Example

class Shark: class Shark:

name = "fish" def init (self, name):

[Link] = name

obj = Shark() obj1 = Shark("Sammy")

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 derived_class_name(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>

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]()

# Create Base class Output


class Vehicle: BMW X1 Black 35000
BMW X1 5

def init (self, name, color, price):


[Link] = name
[Link] = color
[Link] = price

def info(self):
print([Link], [Link], [Link])

# Create a Child class


class Car(Vehicle):
def change_gear(self, no):
print([Link], no)

# Create object for Car


obj = Car('BMW X1', 'Black', 35000)
[Link]()
obj.change_gear(5)

10 [Link],CSD dept,Aitam
Python Programming UNIT-V

ii. Multi-Level inheritance:

 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

class Animal: dog barking


def speak(self): Animal Speaking
print("Animal Speaking") Eating bread...
class Dog(Animal):
def bark(self):
print("dog barking")
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d =DogChild()
[Link]()
[Link]()
[Link]()

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()

iii. Multiple inheritance:

 Python provides us the flexibility to inherit multiple base classes in the child class.

 The syntax to perform multiple inheritance is:

Syntax
class Base1:
<class-suite>

class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>

class Derived_class_name(Base1, Base2, ....... 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))

Advantages of Inheritance in Python:

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.

Disadvantages of Inheritance in Python:

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.

1. Introduction to Regular Expression:

 A Regular Expression is a sequence of characters that forms a search pattern.


 RegEx can be used to check if a string contains the specified search pattern.
 A regular expression is a set of characters with highly specialized syntax that we can use
to find or match other characters or groups of characters.
 In short, regular expressions, or Regex, are widely used in the UNIX world.
 For example,

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.

Expression String Matched?


^a...s$ abs No match
alias Match
abyss Match
Alias No match
An abacus No match

 The re-module in Python gives full support for regular expressions.


 The re module raises the [Link] exception whenever an error occurs while
implementing or using a regular expression.
 Python has a built-in package called re, which can be used to work with Regular
Expressions.

14 [Link],CSD dept,Aitam
Python Programming UNIT-V

 Import the re module:

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( [ ] ):

 Square brackets specifies a set of characters you wish to match.


Expression String Matched?
[abc] a 1 match
ac 2 matches
Hey Jude No match
abc de ca 5 matches

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.

Expression String Matched?


^a a 1 match
abc 1 match
bac No match

^ab abc 1 match

acb No match (starts with a but not followed by b )

iv. Dollar($):
 The dollar symbol $ is used to check if a string ends with a certain character.

Expression String Matched?


a$ a 1 match
formula 1 match
cab No match

v. Star(*):
 The star symbol * matches zero or more occurrences of the pattern left to it.

Expression String Matched?

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 .Question Mark(?):


The question mark symbol ? matches zero or one occurrence of the pattern left to it.

Expression String Matched?


ma?n mn 1 match
man 1 match
maaan No match (more than one a character)
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.

Expression String Matched?

17 [Link],CSD dept,Aitam
Python Programming UNIT-V

a{2,3} abc dat No match


abc data 1 match (at daat)
aabc daaat 2 matches (at aabc and daaat)
aabc daaaat 2 matches (at aabc and daaaat)

 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)

 Here, a|b match any string that contains either a or b


x. Group ( ):
 Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string that
matches either a or b or c followed by xz
Expression String Matched?
(a|b|c)xz ab xz No match
Abxz 1 match (match at abxz )
axz cabxz 2 matches (at axzbc cabxz )

xi. Backslash(\):
 Backlash \ is used to escape various characters including all metacharacters. For
example,

18 [Link],CSD dept,Aitam
Python Programming UNIT-V

 \$a match if a string contains $ followed by a. Here, $ is not interpreted by a RegEx


engine in a special way.
 If you are unsure if a character has special meaning or not, you can put \ in front of it.
This makes sure the character is not treated in a special way.
Special Sequences:
 Special sequences make commonly used patterns easier to write. Here's a list of special
sequences:
 \A - Matches if the specified characters are at the start of a string.
Expression String Matched?
\Athe the sun Match
In the sun No match

 \b - Matches if the specified characters are at the beginning or end of a word.


Expression String Matched?
\bfoo football Match

a football Match

afootball No match

foo\b the foo Match

the afoo test Match

the afootest No match


 \B - Opposite of \b. matches if the specified characters are not at the beginning or end of
a word.
Expression String Matched?
\Bfoo football No match
a football No match
afootball Match
foo\B the foo No match
the afoo test No match
the afootest Match

19 [Link],CSD dept,Aitam
Python Programming UNIT-V

 \d - Matches any decimal digit. Equivalent to [0-9]


Expression String Matched?
\d 12abc3 3 matches (at 12abc3)
Python No match

 \D - Matches any non-decimal digit. Equivalent to [^0-9]


Expression String Matched?
\D 1ab34"50 3 matches (at 1ab34"50 )
1345 No match

 \s - Matches where a string contains any whitespace character. Equivalent to [ \t\n\r\f\v].


Expression String Matched?
\s Python RegEx 1 match
PythonRegEx No match
 \S - Matches where a string contains any non-whitespace character. Equivalent to [^
\t\n\r\f\v].
Expression String Matched?
\S ab 2 matches (at a b )
No match

 \w - Matches any alphanumeric character (digits and alphabets). Equivalent to [a-zA-Z0-


9_]. By the way, underscore _ is also considered an alphanumeric character.

Expression String Matched?


\w 12&": ;c 3 matches (at 12&": ;c)
%"> ! No match

 \W - Matches any non-alphanumeric character. Equivalent to [^a-zA-Z0-9_]


Expression String Matched?

20 [Link],CSD dept,Aitam
Python Programming UNIT-V

\W 1a2%c 1 match (at 1a2%c )


Python No match

 \Z - Matches if the specified characters are at the end of a string.


Expression String Matched?
Python\Z I like Python 1 match
I like Python Programming No match
Python is fun. No match

Meta characters:

Character Description Example


[] A set of characters "[a-m]"
\ Signals a special sequence (can also be used to escape "\d"
special characters)
. Any character (except newline character) "he..o"
^ Starts with "^hello"
$ Ends with "planet$"
* Zero or more occurrences "he.*o"
+ One or more occurrences "he.+o"
? Zero or one occurrences "he.?o"
{} Exactly the specified number of occurrences "he.{2}o"
| Either or "falls|stays"
() Capture and group

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

Character Description Example


\A Returns a match if the specified characters are at the "\AThe"
beginning of the string
\b Returns a match where the specified characters are at the r"\bain"
beginning or at the end of a word r"ain\b"
(the "r" in the beginning is making sure that the string is
being treated as a "raw string")
\B Returns a match where the specified characters are present, r"\Bain"
but NOT at the beginning (or at the end) of a word r"ain\B"
(the "r" in the beginning is making sure that the string is
being treated as a "raw string")
\d Returns a match where the string contains digits (numbers "\d"
from 0-9)
\D Returns a match where the string DOES NOT contain digits "\D"

\s Returns a match where the string contains a white space "\s"


character
\S Returns a match where the string DOES NOT contain a white "\S"
space character
\w Returns a match where the string contains any word "\w"
characters (characters from a to Z, digits from 0-9, and the
underscore _ character)
\W Returns a match where the string DOES NOT contain any "\W"
word characters
\Z Returns a match if the specified characters are at the end of "Spain\Z"
the string

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

findall Returns a list containing all matches

search Returns a Match object if there is a match anywhere in the string

split Returns a list where the string has been split at each match

sub Replaces one or many matches with a string

i. findall() Function

 The findall() function returns a list containing all matches.

Example-1

#Print a list of all matches:

import re

txt = "The rain in Spain"

x = [Link]("ai", txt)

print(x)

Example-2

# Program to extract numbers from a string


import re
string = 'hello 12 hi 89. Howdy 34'

23 [Link],CSD dept,Aitam
Python Programming UNIT-V

pattern = '\d+'
result = [Link](pattern, string)
print(result)

# Output: ['12', '89', '34']

The list contains the matches in the order they are found.

 If no matches are found, an empty list is returned

ii. 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.

 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

 Syntax is: match = [Link](pattern, str)

Example-1

#Search for the first white-space character in the string

import re

txt = "The rain in Spain"

x = [Link]("\s", txt)

print("The first white-space character is located in position:", [Link]())

24 [Link],CSD dept,Aitam
Python Programming UNIT-V

Example-2

import re

string = "Python is fun"

# check if 'Python' is at the beginning

match = [Link]('\APython', string)

if match:

print("pattern found inside the string")

else:

print("pattern not found")

Output: pattern found inside the string

iii. split() Function

 The split() function returns a list where the string has been split at each match:

Example-1

# Split at each white-space character :

import re

txt = "The rain in Spain"

x = [Link]("\s", txt)

print(x)

25 [Link],CSD dept,Aitam
Python Programming UNIT-V

Example-2

import re

string = 'Twelve:12 Eighty nine:89.'

pattern = '\d+'

result = [Link](pattern, string)

print(result)

Output: ['Twelve:', ' Eighty nine:', '.']

iv. sub() Function:

 The sub() function replaces the matches with the text of your choice

 The syntax of [Link]() is:


[Link](pattern, replace, string)
 The method returns a string where matched occurrences are replaced with the content
of replace variable.

Example-1

# Replace every white-space character with the number 9:

import re

txt = "The rain in Spain"

x = [Link]("\s", "9", txt)

print(x)

Example-2

# Program to remove all whitespaces

import re

string = 'abc 12\

26 [Link],CSD dept,Aitam
Python Programming UNIT-V

de 23 \n f45 6'

pattern = '\s+'

replace = ''

new_string = [Link](pattern, replace, string)

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

# Do a search that will return a Match Object :

import re

txt = "The rain in Spain"

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

# The regular expression looks for any words that


starts with an upper case "S"::

import re

txt = "The rain in Spain"

x = [Link](r"\bS\w+", txt)

print([Link]())

ii. string:

 It returns the string passed into the function

Example

# Print the string passed into the function

import re

txt = "The rain in Spain"

x = [Link](r"\bS\w+", txt)

print([Link])

iii. group():

 It returns the part of the string where there was a match

28 [Link],CSD dept,Aitam
Python Programming UNIT-V

Example-1

# Print the string passed into the function

import re

txt = "The rain in Spain"

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

You might also like