Python Unit 1
Python Unit 1
Introduction
Manali Gupta
B.Tech 2nd semester
1
7/27/2021
Content
7/27/2021 3
Course Outcome
7/27/2021 4
CO-PO and PSO Mapping
Course At the end of course , the student will be able : Bloom’s
Outcome Knowledge
( CO) Level (KL)
CO1 Define classes and create instances in python. K1, K2
7/27/2021 5
CO-PO and PSO Mapping
Mapping of Course Outcomes and Program Outcomes:
Programming in Python
PO
CO.K PO1 PO2 PO3 4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1
CO2
CO3
CO4
CO5
Average
Mapping of Course Outcomes and Program Specific Outcomes:
Programming in Python
CO.K PSO1 PSO2 PSO3 PSO4
CO1
CO2
CO3
CO4
CO5
7/27/2021
Average 6
Unit Objective
7/27/2021 7
Prerequisite and Recap
7/27/2021 8
Introduction : OOPs concept
Object-oriented programming is a programming paradigm that provides a means
f structuring programs so that properties and behaviours are bundled into individu
bjects.
object-oriented programming is an approach for modelling concrete, real-world
hings, like cars, as well as relations between things, like companies and employee
tudents and teachers, and so on.
In this approach , data and functions are combined to form a class.
or example:
Object Data or attribute Functions/methods
Person Name, age ,gender Speak(),walk() etc.
Polygon Vertices ,border ,color Draw(),erase() etc.
Computer Brand, resolution,price Display(),printing() etc.
7/27/2021 9
Introduction : Python Classes and Objects
7/27/2021 10
Introduction : Python Classes and Objects
Create a Class
•Starts with a keyword class followed by the class_name and a colon:
•Similar to function definition.
Syntax:
class class_name:
<statement-1>
<statement-2>
……
<statement-n>
Example:
Create a class named MyClass, with a property named x:
class MyClass: Output:
x=5
print(MyClass) <class '__main__.MyClass'>
7/27/2021 11
Introduction : Python Classes and Objects
Create Object:
•Creating an object or instance of a class is known as class instantiation
•We can use the class name to create objects:
Syntax:
Object_name =class_name()
# using this syntax ,an empty object of a class is created.
Accessing a class member:
•The object can access class variables and class methods using dot(.) operator.
Example:
Create an object named p1, and print the value of x: Output:
p1 = MyClass() 5
print(p1.x)
7/27/2021 12
Introduction : Python Classes and Objects
7/27/2021 13
Introduction : Python Classes and Objects
Example:
Create a class named Person, use the __init__() method to assign values for name and
age: Another way:
class Person:
def __init__(self, name, age):
class Person:
print(“In class method”)
def __init__(self, name, age): self.name = name
self.name = name self.age = age
self.age = age print(“the values are”,name,age)
p1=Person(“john”,36)
Output:
p1 = Person("John", 36)
Output:
In class method
print(p1.name)
John
The values are:
36
print(p1.age) John 36
7/27/2021 14
Class Variables and Instance Variables
Variables are essentially symbols that stand in for a value we’re using in a program.
Object-oriented programming allows for variables to be used at the class level or the
instance level.
Class Variables
• Declared inside the class definition (but outside any of the instance methods).
• They are not tied to any particular object of the class, hence shared across all the
objects of the class.
• Modifying a class variable affects all objects instance at the same time.
class Car:
wheels = 4 # <- Class variable
def __init__(self, name):
self.name = name # <- Instance variable
Above is the basic, no-frills Car class defined. Each instance of it will have class
variable wheels along with the instance variable name.
Let’s instantiate the class to access the variables:
mercedes=Car("mercedes")
print(mercedes.wheel)# access of class variable through object
print(Car.wheel) )# access of class variable through class
print(mercedes.name) )# access of instance variable through object
Important point:
1. Generally , Class variable is used to define constant with a particular class or provide default
attribute.
2. Another use of class variable is to count the number of objects created.
class Fruits(object):
count = 0
Output:
def __init__(self, name, count):
self.name = name 3
self.count = count 4
Fruits.count = Fruits.count + count 7
7
7
def main():
apples = Fruits("apples", 3);
pears = Fruits("pears", 4);
print (apples.count)
print (pears.count)
print (Fruits.count)
print (apples.__class__.count) # This is Fruit.count
print (type(pears).count) # So is this
if __name__ == '__main__':
main()
Sumit Malik CS201 Module 3
7/27/2021 19
Demonstrate the use of variable defined on the class level
class example:
staticVariable = 9 # Access through class
7/27/2021 21
Introduction : Python Classes and
Objects(Self Parameter)
•Creating object using self argument:
Example:
Class Myclass:
a=10
def func(self):
return “using self”
# instance an object
ob=Myclass()
print(ob.func()) # output : using self
print(Myclass.func(ob)) # output : using self
7/27/2021 22
Introduction : Python Classes and Objects
Example:
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
Output:
7/27/2021 25
Python Encapsulation
Python Encapsulation
• Using OOP in Python, we can restrict access to methods and variables.
• In Python, we denote private attributes using underscore as the prefix i.e single
_ or double __.
7/27/2021 26
Python Encapsulation
Example : Data Encapsulation in Python
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
7/27/2021 27
Python Encapsulation
7/27/2021 28
Python Encapsulation
7/27/2021 29
Data Hiding
Data Hiding:
• An object’s attributes may or may not be visible outside the class
definition.
• In Python, we use double underscore before the attributes name to make them
inaccessible/private or to hide them.
• The attributes with prefix double underscore not visible outside the class.
7/27/2021 30
Data Hiding
Example:
class MyClass:
__hiddenVar = 12
def add(self, increment):
self.__hiddenVar += increment
print (self.__hiddenVar)
myObject = MyClass()
15
myObject.add(3) 23
myObject.add (8) 23
print(Myobject.__hiddenVar)# Error as not accessible outside
print (myObject._MyClass__hiddenVar)
7/27/2021 31
Data Hiding
Example:
class Car:
__maxspeed = 0
__name = ""
def __init__(self):
self.__maxspeed = 200
self.__name = "Supercar"
def drive(self):
print('driving. maxspeed ' + str(self.__maxspeed))
redcar = Car()
redcar.drive()
redcar.__maxspeed = 10 # will not change variable because its private
redcar.drive()
7/27/2021 32
Data Hiding
Example:
class Car:
__maxspeed = 0
__name = ""
def __init__(self):
self.__maxspeed = 200
self.__name = "Supercar"
def drive(self):
print('driving. maxspeed ' + str(self.__maxspeed))
def setMaxSpeed(self,speed):
self.__maxspeed = speed
redcar = Car()
redcar.drive()
redcar.setMaxspeed = 320 # will change variable
redcar.drive()
7/27/2021 33
Introduction to Methods:
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the
object.
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
Output:
def myfunc(self):
print("Hello my name is " + self.name)
Hello my name is John
p1 = Person("John", 36)
p1.myfunc()
7/27/2021 34
Instance methods, Class method, static
methods
Python’s data model, Python offers three types of methods namely instance, class and static
methods.
Instance or object methods:
• They are most widely used methods.
• Instance method receives the instance of the class as the first argument, which by
convention is called self, and points to the instance of class
• However it can take any number of arguments.
Using the self parameter, we can access the other attributes and methods on the same
object and can change the object state.
• Also, using the self.__class__ attribute, we can access the class attributes, and can
change the class state as well.
• Therefore, instance methods gives us control of changing the object as well as the
class state.
• A built-in example of an instance method is str.upper()
>>> "welcome".upper() # called on the str object
7/27/2021 'WELCOME' Sumit Malik CS201 Module 3
35
Example :Instance Methods
Write a program to deposit or withdraw money in a bank account.
account=Account()
ass Account:
account.deposit()
def __init__(self):
account.withdraw()
self.balance=0
account.enquiry()
print(“New Account Created”)
def deposit(self):
Output:
amount=float(input(“enter amount to deposit:”))
New Account created
self.balance+=amount
enter amount to deposit: 1000
def withdraw(self):
New Balance:1000.000000
amount=float(input(“enter amount to withdraw:”))
enter amount to withdraw:25.23
if amount> self.balance:
New Balance:974.770000
print(“Insufficient balance”)
Balance:974.770000
else:
self.balance-=amount
print(New Balance”, self.balance)
def enquiry(self):
print(“Balance”,self.balance)
Sumit Malik CS201 Module 3
7/27/2021 36
Decorators Before :Class and static Methods
Decorators are very powerful and useful tool in Python since it allows programmers to
modify the behaviour of function or class.
Decorators allow us to wrap another function in order to extend the behaviour of the
wrapped function, without permanently modifying it.
Before diving deep into decorators let us understand some concepts that will come in
handy in learning the decorators.
function_to_be_used()
Output: Output:
Area=100 Area=100
Sumit Malik CS201 Module 3
7/27/2021 42
Static Methods
• A static method is marked with a @staticmethod decorator to flag it as static.
• It does not receive an implicit first argument (neither self nor cls).
• It can also be put as a method that “does’t know its class”.
Hence a static method is merely attached for convenience to the class object.
• A static method can be called either on the class or an instance.
• Hence static methods can neither modify the object state nor class state. They
are primarily a way to namespace our methods.
• Syntax for Static Method
class my_class:
@staticmethod
def function_name(arguments):
#Function Body
return value Sumit Malik CS201 Module 3
7/27/2021 43
Static Methods
class Choice:
def __init__(self, subjects):
self.subjects=subjects
@static method
def validate_subject(subjects):
if “CSA” in subjects:
print(“This option is no longer available”)
else:
return True
Subjects=[“DS”,”CSA”,”Foc”,”OS”,”TOC”]
if all(Choice.validate_subjects(i) for I in subjects):
ch=Choice(subjects)
print(“You have been alloted the subjects:”,subjects)
OUTPUT:
This option is no longer available.
Sumit Malik CS201 Module 3
7/27/2021 44
What are the differences between Classmethod and StaticMehtod?
The class method takes cls (class) as first argument. The static method does not take any specific
parameter.
Class method can access and modify the class Static Method cannot access or modify the class
state. state.
The class method takes the class as parameter to Static methods do not know about class state.
know about the state of that class. These methods are used to do some utility tasks by
taking some parameters.
@classmethod decorator is used here. @staticmethod decorator is used here.
Types of constructors :
Default constructor :The default constructor is simple constructor which doesn’
accept any arguments.
It’s 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 take 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.
For example, when you add two numbers using the + operator, internally, the
__add__() method will be called.