OOPS in python
• An object is any entity that has attributes and behaviors. For example,
a parrot is an object. It has
• attributes - name, age, color, etc.
• behavior - dancing, singing, etc.
• class Parrot:
• # class attribute
• name = ""
• age = 0
• # create parrot1 object
• parrot1 = Parrot()
• parrot1.name = "Blu"
• parrot1.age = 10
• # create another object parrot2
• parrot2 = Parrot()
• parrot2.name = "Woo"
• parrot2.age = 15
• # access attributes
• print(f"{parrot1.name} is {parrot1.age} years old")
• print(f"{parrot2.name} is {parrot2.age} years old")
Python Inheritance
Inheritance is a way of creating a new class for using
details of an existing class without modifying it.
• The newly formed class is a derived class (or child
class). Similarly, the existing class is a base class (or
parent class).
class Animal:
dog1 = Dog()
def eat(self):
# Calling members of the base class print( "I can eat!")
dog1.eat()
dog1.sleep() def sleep(self):
print("I can sleep!")
# Calling member of the derived class
dog1.bark(); # derived class
class Dog(Animal):
def bark(self):
print("I can bark! Woof woof!!")
Python Encapsulation
• Encapsulation refers to the bundling of attributes and
methods inside a single class.
• It prevents outer classes from accessing and changing
attributes and methods of a class. This also helps to
achieve data hiding.
• In Python, we denote private attributes using underscore as the prefix
i.e single _ or double __
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()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
Polymorphism in Python
• What is Polymorphism?
• It refers to the use of a single type entity (method,
operator or object) to represent different types in
different scenarios.
• Polymorphism in addition operator
• Polymorphic len() function
• print(len("Programiz"))
• print(len(["Python", "Java", "C"]))
• print(len({"Name": "John", "Address": "Nepal"}))
• print(len("Programiz"))
• print(len(["Python", "Java", "C"]))
• print(len({"Name": "John", "Address": "Nepal"}))
Python Try Except
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The else block lets you execute code when there is no error.
• The finally block lets you execute code, regardless of the result of the
try- and except blocks.
try:
print(x)
except:
print("An exception occurred")
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
else:
print("Nothing went wrong")
Finally
The finally block, if specified, will be executed regardless if the try block
raises an error or not.
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
x = -1
if x < 0:
raise Exception("Sorry, no numbers below
zero")
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")