You are on page 1of 18

Object-Oriented Programming in Python

Object-oriented programming is a programming paradigm that provides a means of structuring


programs so that properties and behaviors are bundled into individual objects.

For instance, an object could represent a person with properties like a name, age, and address
and behaviors such as walking, talking, breathing, and running. Or it could represent
an email with properties like a recipient list, subject, and body and behaviors like adding
attachments and sending.

Put another way, object-oriented programming is an approach for modelling concrete,


real-world things, like cars, as well as relations between things, like companies and
employees, students and teachers, and so on. OOP models real-world entities as software
objects that have some data associated with them and can perform certain functions.

Another common programming paradigm is procedural programming, which structures a


program like a recipe in that it provides a set of steps, in the form of functions and code blocks
that flow sequentially in order to complete a task.

The key takeaway is that objects are at the center of object-oriented programming in Python, not
only representing the data, as in procedural programming, but in the overall structure of the
program as well.

Define a Class in Python


Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class:

class MyClass:

x = 5

print(MyClass)

Create Object
Now we can use the class named MyClass to create objects:

class MyClass:

x = 5

p1 = MyClass()

print(p1.x)
The __init__ () Function
The examples above are classes and objects in their simplest form, and are not really useful in real life
applications.

To understand the meaning of classes we have to understand the built-in __init__() function.

All classes have a function called __init__(), which is always executed when the class is being
initiated.

Use the __init__() function to assign values to object properties, or other operations that are
necessary to do when the object is being created:

Example

Create a class named Person, use the __init__() function to assign values for name and age:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

Note: The __init__() function is called automatically every time the class is being used to create a new
object.

Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.

Let us create a method in the Person class:

Example

Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()
Note: The self parameter is a reference to the current instance of the class, and is used to access
variables that belong to the class.

The self Parameter


The self parameter is a reference to the current instance of the class, and is used to access variables
that belongs to the class.

It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class:

class Person:
def __init__(p, name, age):
p.name = name
p.age = age

def myfunc(abc):
print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

Modify Object Properties


You can modify properties on objects like this:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)

p1.age = 40

print(p1.age)

Delete Object Properties


You can delete properties on objects by using the del keyword:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)

del p1.age

print(p1.age)

Delete Objects
You can delete objects by using the del keyword:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def myfunc(self):
print("Hello my name is " + self.name)

p1 = Person("John", 36)

del p1

print(p1)

The pass Statement


class definitions cannot be empty, but if you for some reason have a class definition with no content,
put in the pass statement to avoid getting an error.

class Person:

pass

# having an empty class definition like this, would raise an error without the pass statement
Constructors in Python
Constructors are generally used for instantiating an object. The task of constructors is to
initialize(assign values) to the data members of the class when an object of the class is
created.

In Python the __init__() method is called the constructor and is always called when an object is
created.

Syntax of constructor declaration:

def __init__(self):

# body of the constructor

Types of constructors :
default constructor: The default constructor is a simple constructor which doesn’t accept any
arguments. Its definition has only one argument which is a reference to the instance being
constructed.

parameterized constructor: constructor with parameters is known as parameterized


constructor. The parameterized constructor takes its first argument as a reference to the instance
being constructed known as self and the rest of the arguments are provided by the programmer.

Example of default constructor :

class subname:

# default constructor
def __init__(self):
self.sname = "Python"

# a method for printing data members


def print_subname(self):
print(self.sname)

# creating object of the class


obj = subname()

# calling the instance method using the object obj


obj.print_subname()

Example of the parameterized constructor :

class Addition:
first = 0
second = 0
answer = 0
# parameterized constructor
def __init__(self, f, s):
self.first = f # 1000
self.second = s # 2000

def display(self):
print("First number = " + str(self.first))
print("Second number = " + str(self.second))
print("Addition of two numbers = " +
str(self.answer))

def calculate(self):
self.answer = self.first + self.second

# creating object of the class


# this will invoke parameterized constructor
obj = Addition(1000, 2000)

# perform Addition
obj.calculate()

# display result
obj.display()

Destructors in Python
Destructors are called when an object gets destroyed. In Python, destructors are not needed as
much needed in C++ because Python has a garbage collector that handles memory management
automatically.

The __del__() method is a known as a destructor method in Python. It is called when all
references to the object have been deleted i.e when an object is garbage collected.

Syntax of destructor declaration :

def __del__(self):

# body of destructor

Note : A reference to objects is also deleted when the object goes out of reference or when the
program ends.

Example 1 : Here is the simple example of destructor. By using del keyword we deleted the all
references of object ‘obj’, therefore destructor invoked automatically.

Note : The destructor was called after the program ended or when all the references to object are
deleted i.e when the reference count becomes zero, not when object went out of scope.

# Python program to illustrate destructor

class Employee:

# Initializing
def __init__(self):

print('Employee created.')

# Deleting (Calling destructor)

def __del__(self):

print('Destructor called, Employee deleted.')

obj = Employee()

del obj

Example 2 :This example gives the explanation of above mentioned note. Here, notice that the
destructor is called after the ‘Program End…’ printed.

# Python program to illustrate destructor

class Employee:

# Initializing

def __init__(self):

print('Employee created')

# Calling destructor

def __del__(self):

print("Destructor called")

def Create_obj():

print('Making Object...')

obj = Employee()

print('function end...')

return obj

print('Calling Create_obj() function...')

obj = Create_obj()

print('Program End...')
Python built-in class functions-getattr, setattr, delattr, hasattr
The built-in functions defined in the class are described in the following table.

SN Function Description

1 getattr(obj,name,default) It is used to access the attribute of the object.

2 setattr(obj, name,value) It is used to set a particular value to the specific


attribute of an object.

3 delattr(obj, name) It is used to delete a specific attribute.

4 hasattr(obj, name) It returns true if the object contains some


specific attribute.

getattr():
The only use of Python getattr() function is to get the value of an object’s attribute and if no
attribute of that object is found, default value is returned.

Basically, returning the default value is the main reason you should use getattr() function.
getattr() function accepts multiple parameters.

syntax :

getattr(object, attribute_name [, default])

where,

object — object of the class whose attribute value is to be returned.

attribute_name — attribute’s name.

default (Optional) — value that is returned when the attribute is not found.

If attribute_name passed to getattr() is not found or available in the class, default value comes
into picture.

This enables us to complete some of our incomplete data and finish the program execution
without any errors.

Let us see an example-


Setattr():
Similarly, we have something to set the attribute values of an object, setattr().

Syntax:

setattr(object, name, value)

where,

object — object whose attribute has to be set.

attribute_name — attribute name for which we need to set the value.

attribute_value — value of the attribute to be set.

Let us see an example-

You can also set an attribute and its value using setattr() function , even if it is not in the class
currently, however it is object specific. In the below example, we are trying to set a new attribute
for the object ‘emp_name’ from outside the class.
hasattr()
There is a inbuilt function to check if the object has the atrribute present or not. It returns true
if an object has the given attribute and false if it does not.

Syntax:

hasattr(object, name)

where,

object — object name of the class

name — attribute name to be checked.

delattr():
The delattr() deletes an attribute from the object (if allowed).

Syntax:

delattr(class_name, name)

where,

class_name — name of the class

name — attribute name to be deleted.


Python Regular Expressions and String Processing
The regular expressions can be defined as the sequence of characters which are used to search
for a pattern in a string.

The module re provides the support to use regex in the python program.

The re module throws an exception if there is some error while using the regular expression.

The re module must be imported to use the regex functionalities in python.

Syntax:

import re

Regex Functions

The following regex functions are used in the python.

SN Function Description

1 match This method matches the regex pattern in the string with the
optional flag. It returns true if a match is found in the string
otherwise it returns false.

2 search This method returns the match object if there is a match found in
the string.

3 findall It returns a list that contains all the matches of a pattern in the
string.

4 split Returns a list in which the string has been split in each match.

5 sub Replace one or many matches in the string.

Forming a regular expression


A regular expression can be formed by using the mix of meta-characters, special sequences,
and sets.
Meta-Characters
Metacharacter is a character with the specified meaning.

Metacharacter Description Example

[] It represents the set of characters. "[a-z]"

\ It represents the special sequence. "\r"

. It signals that any character is present at some specific place. "Ja.v."

^ It represents the pattern present at the beginning of the string. "^Java"

$ It represents the pattern present at the end of the string. "point"

* It represents zero or more occurrences of a pattern in the string. "hello*"

+ It represents one or more occurrences of a pattern in the string. "hello+"

{} The specified number of occurrences of a pattern the string. "java{2}"

| It represents either this or that character is present. "java|point"

() Capture and group


Special Sequences
Special sequences are the sequences containing \ followed by one of the characters.

Character Description

\A It returns a match if the specified characters are present at the beginning of the string.

\b It returns a match if the specified characters are present at the beginning or the end of the
string.

\B It returns a match if the specified characters are present at the beginning of the string but
not at the end.

\d It returns a match if the string contains digits [0-9].

\D It returns a match if the string doesn't contain the digits [0-9].

\s It returns a match if the string contains any white space character.

\S It returns a match if the string doesn't contain any white space character.

\w It returns a match if the string contains any word characters.

\W It returns a match if the string doesn't contain any word.

\Z Returns a match if the specified characters are at the end of the string.

Sets
A set is a group of characters given inside a pair of square brackets. It represents the special
meaning.

SN Set Description

1 [arn] Returns a match if the string contains any of the specified characters in the set.

2 [a-n] Returns a match if the string contains any of the characters between a to n.

3 [^arn] Returns a match if the string contains the characters except a, r, and n.

4 [0123] Returns a match if the string contains any of the specified digits.
5 [0-9] Returns a match if the string contains any digit between 0 and 9.

6 [0-5][0-9] Returns a match if the string contains any digit between 00 and 59.

10 [a-zA-Z] Returns a match if the string contains any alphabet (lower-case or upper-case).

The findall() function


This method returns a list containing a list of all matches of a pattern within the string.

It returns the patterns in the order they are found. If there are no matches, then an empty list is
returned.

Example

import re

str ="I am learninig Python Programming, Python is very


easy language"

matches = re.findall("Python", str)

print(matches)
Output:

['Python', 'Python']

The match object Function


The match object contains the information about the search and the output.

If there is no match found, the None object is returned.

Example

import re

str ="I am learninig Python Programming, Python is very


easy language"

matches = re.search("Python", str)

print(type(matches))

print(matches) #matches is the search object


Output:
<class 're.Match'>

<re.Match object; span=(15, 21), match='Python'>

The Match object methods


There are the following methods associated with the Match object.

• span(): It returns the tuple containing the starting and end position of the match.
• string(): It returns a string passed into the function.
• group(): The part of the string is returned where the match is found.

Example

import re

str ="I am learninig Python Programming, Python is very


easy language"

matches = re.search("Python", str)

print(matches.span())

print(matches.group())

print(matches.string)

Output:

(15, 21)

Python

I am learninig Python Programming, Python is very easy


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

import re

txt = "I am learninig Python Programming"


x = re.search("\s", txt)

print("The first white-space character is located in


position:", x.start())

y = re.search("Java", txt)
print(y)

Output:
The first white-space character is located in position: 1
None

The split () Function


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

Example:

import re

#Split the string at every white-space character:

txt = "I am learninig Python Programming"


x = re.split("\s", txt)
print(x)

Output:
['I', 'am', 'learninig', 'Python', 'Programming']

You can control the number of occurrences by specifying the maxsplit parameter:

Example:
import re

#Split the string at every white-space character:

txt = "I am learninig Python Programming"


x = re.split("\s", txt,1)
print(x)
Output:
['I', 'am learninig Python Programming']

The sub() Function

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

Example:

import re

#Replace all white-space characters with the digit "9":

txt = "I am learninig Python Programming"

x = re.sub("\s", "@", txt)


print(x)

Output:
I@am@learninig@Python@Programming

You can control the number of replacements by specifying the count parameter:

Example:
import re

#Replace the first two occurrences of a white-space


character with the digit 9:

txt = "I am learninig Python Programming"

x = re.sub("\s", "@", txt, 2)


print(x)

Output:
I@am@learninig Python Programming

You might also like