Professional Documents
Culture Documents
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.
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.
Create a 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.
Example
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.
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()
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)
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)
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.
def __init__(self):
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.
class subname:
# default constructor
def __init__(self):
self.sname = "Python"
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
# 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.
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.
class Employee:
# Initializing
def __init__(self):
print('Employee created.')
def __del__(self):
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.
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
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
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 :
where,
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.
Syntax:
where,
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,
delattr():
The delattr() deletes an attribute from the object (if allowed).
Syntax:
delattr(class_name, name)
where,
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.
Syntax:
import re
Regex Functions
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.
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.
\S It returns a match if the string doesn't contain any white space character.
\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).
It returns the patterns in the order they are found. If there are no matches, then an empty list is
returned.
Example
import re
print(matches)
Output:
['Python', 'Python']
Example
import re
print(type(matches))
• 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
print(matches.span())
print(matches.group())
print(matches.string)
Output:
(15, 21)
Python
If there is more than one match, only the first occurrence of the match will be returned:
Example:
import re
y = re.search("Java", txt)
print(y)
Output:
The first white-space character is located in position: 1
None
Example:
import re
Output:
['I', 'am', 'learninig', 'Python', 'Programming']
You can control the number of occurrences by specifying the maxsplit parameter:
Example:
import re
The sub() function replaces the matches with the text of your choice:
Example:
import re
Output:
I@am@learninig@Python@Programming
You can control the number of replacements by specifying the count parameter:
Example:
import re
Output:
I@am@learninig Python Programming