Python Unit I
Python Unit I
Class − A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members and methods,
accessed via dot notation.
Class variable − A variable that is shared by all instances of a class. Class variables
are defined within a class but outside any of the class's methods. Class variables are
not used as frequently as instance variables are.
Data member − A class variable or instance variable that holds data associated with a
class and its objects.
Function overloading − The assignment of more than one behavior to a particular
function. The operation performed varies by the types of objects or arguments
involved.
Instance variable − A variable that is defined inside a method and belongs only to the
current instance of a class.
Inheritance − The transfer of the characteristics of a class to other classes that are
derived from it.
Instance − An individual object of a certain class. An object obj that belongs to a
class Circle, for example, is an instance of the class Circle.
Instantiation − The creation of an instance of a class.
Method − A special kind of function that is defined in a class definition.
Object − A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
Operator overloading − The assignment of more than one function to a particular
operator.
Creating Classes
The class statement creates a new class definition. The name of the class immediately follows
the keyword class followed by a colon as follows −
Class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed via ClassName.__doc__.
The class_suite consists of all the component statements defining class members, data
attributes and functions.
Example
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
The variable empCount is a class variable whose value is shared among all instances
of a this class. This can be accessed as Employee.empCount from inside the class or
outside the class.
The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
You declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self argument to the list for you; you
do not need to include it when you call the methods.
To create instances of a class, we call the class using class name and pass in whatever
arguments its __init__ method accepts.
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
Every Python class keeps following built-in attributes and they can be accessed using dot
operator like any other attribute −
For the above class let us try to access all these attributes −
#!/usr/bin/python
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
Python deletes unneeded objects (built-in types or class instances) automatically to free the
memory space. The process by which Python periodically reclaims blocks of memory that no
longer are in use is termed Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an object's
reference count reaches zero. An object's reference count changes as the number of aliases
that point to it changes.
An object's reference count increases when it is assigned a new name or placed in a container
(list, tuple, or dictionary). The object's reference count decreases when it's deleted with del,
its reference is reassigned, or its reference goes out of scope. When an object's reference
count reaches zero, Python collects it automatically.
Example
This __del__() destructor prints the class name of an instance that is about to be destroyed −
#!/usr/bin/python
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"
pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
When the above code is executed, it produces following result −
Note − Ideally, you should define your classes in separate file, then you should import them
in your main program file using import statement.
Class Inheritance
Instead of starting from scratch, you can create a class by deriving it from a preexisting class
by listing the parent class in parentheses after the new class name.
The child class inherits the attributes of its parent class, and you can use those attributes as if
they were defined in the child class. A child class can also override data members and
methods from the parent.
Syntax
Derived classes are declared much like their parent class; however, a list of base classes to
inherit from is given after the class name −
def parentMethod(self):
print 'Calling parent method'
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
def childMethod(self):
print 'Calling child method'
Similar way, we can derive a class from multiple parent classes as follows −
class A: # define class A
.....
The issubclass(sub, sup) boolean function returns true if the given subclass sub is
indeed a subclass of the superclass sup.
The isinstance(obj, Class) boolean function returns true if obj is an instance of
class Class or is an instance of a subclass of Class
Overriding Methods
We can always override our parent class methods. One reason for overriding parent's
methods is because we may want special or different functionality in our subclass.
#!/usr/bin/python
1
__init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call : obj = className(args)
2
__del__( self )
Destructor, deletes an object
Sample Call : del obj
3
__repr__( self )
Evaluable string representation
Sample Call : repr(obj)
4
__str__( self )
Printable string representation
Sample Call : str(obj)
5
__cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)
Overloading Operators
Suppose you have created a Vector class to represent two-dimensional vectors, what happens
when you use the plus operator to add them
You could, however, define the __add__ method in your class to perform vector addition and
then the plus operator would behave as per expectation −
Example
#!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
Vector(7,8)
Data Hiding
An object's attributes may or may not be visible outside the class definition. You need to
name attributes with a double underscore prefix, and those attributes then are not be directly
visible to outsiders.
Example
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Python protects those members by internally changing the name to include the class name.
You can access such attributes as object._className__attrName. If you would replace your
last line as following, then it works for you −
.........................
print counter._JustCounter__secretCount
When the above code is executed, it produces the following result −
1
2
2
Polymorphism in Python
What is Polymorphism:
The word polymorphism means having many forms. In programming, polymorphism
means the same function name (but different signatures) being used for different types. The
key difference is the data types and number of arguments used in function.
Example of inbuilt polymorphic functions:
# morphic functions
print(len("geeks"))
Output:
5
3
# Polymorphism
return x + y+z
# Driver code
print(add(2, 3))
print(add(2, 3, 4))
Output:
5
9
class India():
def capital(self):
def language(self):
def type(self):
class USA():
def capital(self):
def language(self):
def type(self):
obj_ind = India()
obj_usa = USA()
country.capital()
country.language()
country.type()
Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
In Python, Polymorphism lets us define methods in the child class that have the
same name as the methods in the parent class. In inheritance, the child class inherits the
methods from the parent class. However, it is possible to modify a method in a child class
that it has inherited from the parent class. This is particularly useful in cases where the
method inherited from the parent class doesn’t quite fit the child class. In such cases, we re-
implement the method in the child class. This process of re-implementing a method in the
child class is known as Method Overriding.
class Bird:
def intro(self):
def flight(self):
class sparrow(Bird):
def flight(self):
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
Output:
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
Encapsulation in Python
What is Assertion?
Assertions are statements that assert or state a fact confidently in your program. For example,
while writing a division function, you're confident the divisor shouldn't be zero, you assert
divisor is not equal to zero.
Assertions are simply boolean expressions that check if the conditions return true or not. If it
is true, the program does nothing and moves to the next line of code. However, if it's false,
the program stops and throws an error.
It is also a debugging tool as it halts the program as soon as an error occurs and displays it.
assert <condition>
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)
mark1 = []
print("Average of mark1:",avg(mark1))
Run Code
When we run the above program, the output will be:
AssertionError
We got an error as we passed an empty list mark1 to assert statement, the condition became
false and assert stops the program and give AssertionError.
Now let's pass another list which will satisfy the assert condition and see what will be our
output.
Example 2: Using assert with error message
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
Run Code
Decorators in Python
Decorators are a very powerful and useful tool in Python since it allows programmers to
modify the behaviour of a function or class. Decorators allow us to wrap another function
in order to extend the behaviour of the wrapped function, without permanently modifying
it. But before diving deep into decorators let us understand some concepts that will come in
handy in learning the decorators.
First Class Objects
In Python, functions are first class objects which means that functions in Python can
be used or passed as arguments.
Properties of first class functions:
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists, …
Consider the below examples for better understanding.
Example 1: Treating the functions as objects.
def shout(text):
return text.upper()
print(shout('Hello'))
yell = shout
print(yell('Hello'))
Output:
HELLO
HELLO
In the above example, we have assigned the function shout to a variable. This will not call
the function instead it takes the function object referenced by a shout and creates a second
name pointing to it, yell.
Example 2: Passing the function as an argument
def shout(text):
return text.upper()
def hint(text):
return text.lower()
def greet(func):
print (greeting)
greet(shout)
greet(hint)
Output:
In the above example, the greet function takes another function as a parameter (shout and
hint in this case). The function passed as an argument is then called inside the function
greet.
Generators in Python
def simpleGeneratorFun():
yield 1
yield 2
yield 3
print(value)
Output
1
2
3
# A generator function
def simpleGeneratorFun():
yield 1
yield 2
yield 3
# x is a generator object
x = simpleGeneratorFun()
print(next(x))
print(next(x))
Output
1
2
3
So a generator function returns an generator object that is iterable, i.e., can be used as
an Iterators . As another example, below is a generator for Fibonacci Numbers.
def fib(limit):
a, b = 0, 1
yield a
a, b = b, a + b
print(next(x))
print(next(x))
print(next(x))
print(next(x))
# in loop.
for i in fib(5):
print(i)
Output
0
1
1
2
3
Using for in loop
0
1
1
2
3
Iterators in Python
Iterator in Python is an object that is used to iterate over iterable objects like lists, tuples,
dicts, and sets. The iterator object is initialized using the iter() method. It uses
the next() method for iteration.
1. __iter__(): The iter() method is called for the initialization of an iterator. This returns
an iterator object
2. __next__(): The next method returns the next value for the iterable. When we use a for
loop to traverse any iterable object, internally it uses the iter() method to get an iterator
object, which further uses the next() method to iterate over. This method raises a
StopIteration to signal the end of the iteration.
Python iter() Example
string = "GFG"
ch_iterator = iter(string)
print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))
Output :
G
F
G
Example 1: Creating and looping over an iterator using iter() and next()
Below is a simple Python custom iterator that creates an iterator type that iterates from 10
to a given limit. For example, if the limit is 15, then it prints 10 11 12 13 14 15. And if the
limit is 5, then it prints nothing.
class Test:
# Constructor
self.limit = limit
def __iter__(self):
self.x = 10
return self
def __next__(self):
x = self.x
raise StopIteration
self.x = x + 1;
return x
for i in Test(15):
print(i)
# Prints nothing
for i in Test(5):
print(i)
Output :
10
11
12
13
14
15
Inheritance in Python
Inheritance is the capability of one class to derive or inherit the properties from another
class.
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
Creating a Parent Class
Creating a Person class with Display methods.
class Person(object):
# Constructor
self.name = name
self.id = id
def Display(self):
print(self.name, self.id)
# Driver code
emp.Display()
Output:
Satyam 102
Creating a Child Class
Here Emp is another class which is going to inherit the properties of the Person class(base
class).
class Emp(Person):
def Print(self):
Emp_details.Display()
Emp_details.Print()
Output:
Mayank 103
Emp class called
Example of Inheritance in Python
class Person(object):
# Constructor
self.name = name
# To get name
def getName(self):
return self.name
def isEmployee(self):
return False
class Employee(Person):
def isEmployee(self):
return True
# Driver code
print(emp.getName(), emp.isEmployee())
emp = Employee("Geek2") # An Object of Employee
print(emp.getName(), emp.isEmployee())
Output:
Geek1 False
Geek2 True
Like the Java Object class, in Python (from version 3. x), the object is the root of all
classes.
In Python 3.x, “class Test(object)” and “class Test” are same.
In Python 2. x, “class Test(object)” creates a class with the object as a parent (called a
new-style class), and “class Test” creates an old-style class (without an objecting
parent).
A child class needs to identify which class is its parent class. This can be done by
mentioning the parent class name in the definition of the child class.
# are called.
# parent class
class Person(object):
self.idnumber = idnumber
def display(self):
print(self.name)
print(self.idnumber)
# child class
class Employee(Person):
self.salary = salary
self.post = post
a.display()
Output:
Rahul
886012
‘a’ is the instance created for the class Person. It invokes the __init__() of the referred
class. You can see ‘object’ written in the declaration of the class Person. In Python, every
class inherits from a built-in basic class called ‘object’. The constructor i.e. the ‘__init__’
function of a class is invoked when we create an object variable or an instance of the class.
The variables defined within __init__() are called the instance variables or objects. Hence,
‘name’ and ‘idnumber’ are the objects of the class Person. Similarly, ‘salary’ and ‘post’ are
the objects of the class Employee. Since the class Employee inherits from class Person,
‘name’ and ‘idnumber’ are also the objects of class Emplo yee.