OOPS in Python
OOPS in Python
• An object is any entity that has attributes and behaviors. For example,
a parrot is an object. It has
• # class attribute
• name = ""
• age = 0
• # 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.
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
c = Computer()
c.sell()
• 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"