Oops in Python Notes

 


'''
#Blueprint of an Human Class
class Human:
'Human class imlementation'
def __init__(self,name,age,height): #constructor
self.name = name
self.age = age
self.height = height
# print(id(self))
# self.color = "red"
# self.height = 67
# self.name = "Deepak"
# self.age = 17
def set_age(self,age):
self.age = age
def work(self):
print("Working..")
def eat(self):
print("Eating...")
h = Human("Deepak Singhal",17,56) #Initailizing
# j = Human()
# print(type(h))
# h.work()
# h.eat()
# print(h.age)
# print(h.name)
# print(h.height)
# # h.set_age(25)
# print(h.age)
# print(id(h ))
# print(id(j))

print(Human.__doc__) #to read the documnetation inside the human class
'''
import math


##Inheritence in Python###
# class Pet:
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def Display(self):
# print(f"I'm {self.name} my age is {self.age}")
# def speak(self):
# print("I dont know how to speak")
#
# class Dog(Pet):
# def __init__(self,name,age,color):
# self.color = color
# super().__init__(name,age)
# def speak(self):
# print("Barking...")
#
#
# class Cat(Pet):
# pass
# # def speak(self):
# # print("Meow...")
#
# # timmy = Dog("Timmy",2)
# # print(timmy.name)
# # timmy.speak()
# # timmy.Display()
#
# d = Dog("Tummu",2, "Brown")
# d.speak()
#
# c = Cat("Minza",1)
# c.speak()



###Types of Inheritence###
# #Single Inheritence
# class A:
# def feature1(self):
# print("Feature 1")
#
# class B(A):#This is known as single inheritence
# def feature2(self):
# print("Feature 2")
#
# b = B()
# b.feature1()

# #MultiLevel Inheritence
# class GrandParent:
# def GrandParentFeature(self):
# print("GrandParentFeatures")
#
# class Parent(GrandParent):
# def ParentFeature(self):
# print("Parents Features")
#
# class Child(Parent):#This is known as Multilevel inheritence
# def ChildFeature(self):
# print("Child Features")
#
# c = Child()
# c.GrandParentFeature()
# c.ParentFeature()
# c.ChildFeature()

# #Multiple Inheritence
# class Student:
# def study(self):
# print("Studying")
# class Teacher:
# def teach(self):
# print("Teaching..")
# class Ta(Student, Teacher):#This is known as Multiple inheritence
# def work(self):
# print("working")
#
# T = Ta()
# T.study()
# T.teach()
# T.work()



# #Data Mangling
# class CreditCard:
# def __init__(self,cardNumber):
# self.__cardNumber = cardNumber #Private Attribute
#
# def userCard(self):
# print(f"Credit Card {self.__cardNumber} used")
#
# c = CreditCard(12345)
# # print(c.__cardNumber)#we cant use that because its prinvate
# print(c._CreditCard__cardNumber)
# c.userCard()


##Class Method##
# class Employee:
# totalEmployees = 0 #class Attribute
# def __init__(self,name):
# self.name = name #Instance Attribute
# Employee.totalEmployees += 1
# @classmethod
# def removeEmployee(self):
# Employee.totalEmployees -= 1
#
#
# a = Employee("Deepak")
# print(Employee.totalEmployees)
#
# b = Employee("Deepak")
# print(Employee.totalEmployees)
# Employee.removeEmployee()

# ##Static Methods#3
# class Math:
# @staticmethod
# def square(num):
# return num * num
# a = Math()
# print(a.square(9))
# print(Math.square(8))

# ##Destructor##
# class cat:
# def __init__(self):
# print("Hi, This is Cat!")
# def __del__(self): #destructor
# print("By, From Cat!")
# c = cat()
# print("***")
# print("---")
# print("***")
# del c

# ##Getters and Setters##
# class Cat:
# def __init__(self,color,name):
# self.color = color
# self.name = name
# #setters set the name
# def setColor(self,color):
# self.color = color
# #getters accessing the data members value
# def getName(self):
# return self.name
# def getColor(self):
# return self.color
# a = Cat("Black","joy")
# a.setColor("white")
# print(a.getColor())


# ##Public, Protected, Private ##
# class cat:
# name = "John"#Public
# _color = "Black"#Protected
# __age = 5#private
#
# a = cat()
# print(a.name)
# print(a._color)
# print(a._cat__age)


##__init__ (self) Method##
# --------------------------------
# class Dog:
# def __init__(self,breed,color):#self is a keyword that represents the object calling
# #initilization
# self.breed = breed
# self.color = color
# dog = Dog("x","brown")
# print(dog.breed, end=" ")
# print(dog.color,end=" ")

# #default parrameters
# class Dog:
# def __init__(self,breed="y",color="white"):#default parameters
# self.breed = breed
# self.color = color
# d1 = Dog("x","Brown")
# d2 = Dog()
# print(d1.color)
# print(d2.color)

##Inner class in Python## (Nested Class)
# class outer:
#
# class inner: #inner class
# pass
#
# class innerInner:
# pass
#
# class _Inner:
# pass
# pass

# class lanugage:
# def __init__(self):
# self.language = "Python"
# self.lg = self.specification()
#
# def show(self):
# print("Language",self.language)
# class specification:
# def __init__(self):
# self.type = "High Level"
# self.founded = "1991"
#
# def display(self):
# print("type",self.type)
# print("founded",self.founded)
#
# out = lanugage()
# out.show()
# pool = out.lg
# pool.display()

# #1. Multiple Inner Classes
# class Outer:
# def __init__(self):
# self.inner = self.Inner()
# self._inner = self._Inner()
# def show_classes(self):
# print("This is outer class")
# print(inner)
# print(_inner)
# class Inner:
# def inner_Display(self,msg):
# print("This is Inner Class")
# print(msg)
# class _Inner:
# def inner_display(self,msg):
# print("This is _Inner Class")
# print(msg)
#
# outer = Outer()
# inner = outer.Inner()
# _inner = outer._Inner()
# outer.show_classes()
# print()
# inner.inner_Display("Just Print")
# print()
# _inner.inner_display("Print It")

# #Multilevel Inner Class
# class outer:
# def __init__(self):
# self.inner = self.Inner()
# self.innerinner = self.inner.InnerInner()
# def show_classes(self):
# print("This is outer class")
# print(self.inner)
# class Inner:
# def __init__(self):
# self.innerinner = self.InnerInner()
# def show_classes(self):
# print("Thsi is Inner Class")
# print(self.innerinner)
# class InnerInner:
# def inner_display(self,msg):
# print("This is multilevel inner class")
# print(msg)
# out = outer()
# inner = out.Inner()
# innerinner = inner.InnerInner()
# out.show_classes()
# inner.show_classes()
# innerinner.inner_display("This si print")

##Inheritence##
#1. Single Inheritince
# class Animal():
# def __init__(self):
# print("Animal clas is creaetd")
# def speak(self):
# print("Animal is Speak")
# #Child Class
# class Cat(Animal): #Single Inheritince
# def bark(self):
# print("Barking")
# bob = Cat()
# bob.bark()
# bob.__init__()
# bob.speak()

# #2. Multilevel Inheritence
# class Animal():
# def __init__(self):
# print("Animal clas is creaetd")
# def speak(self):
# print("Animal is Speak")
# #Child Class
# class Cat(Animal): #Single Inheritince
# def bark(self):
# print("Barking")
# class Puppy(Cat):
# def intro(self):
# print("My Name is Puppy")
# bob = Puppy()
# bob.bark()
# bob.__init__()
# bob.speak()
# bob.intro()

# # 3. Multiple Inhertinece
# class Animal():
# def __init__(self):
# print("Animal clas is creaetd")
# def speak(self):
# print("Animal is Speak")
# #Child Class
# class Cat():
# def bark(self):
# print("Barking")
# class Puppy(Animal,Cat): #Multiple, Inheritince
# def intro(self):
# print("My Name is Puppy")
# bob = Puppy()
# bob.bark()
# bob.__init__()
# bob.speak()
# bob.intro()

# #4. Hierarachical Inheritence
# # when both the classes uses the same class for inheritence and make it a tree
# class Animal():
# def __init__(self):
# print("Animal clas is creaetd")
# def speak(self):
# print("Animal is Speak")
# #Child Class
# class Cat(Animal):
# def bark(self):
# print("Barking")
# class Puppy(Animal):
# def intro(self):
# print("My Name is Puppy")
# bob = Puppy()
# bob.__init__()
# bob.speak()
# bob.intro()

##5. Hybrid Inheritence
# when the code use two or more types of inheritence types





# ##Constuctors in Python##
# class Student:
# def __init__(self,name, age):
# print("Hey, Student is created!")
# self.name = name
# self.age = age
# def Display_Details(self):
# print(self.name,self.age)
#
# obj = Student("Deepak Singhal","17 Years old")
# obj.Display_Details()
# print(obj.name)
# print(obj.age)
# #types of constructors
# 1.Default Constructor
# 2.Parameterised Constructor

#Constructor in Inheritence
# class Vehicle:
# def __init__(self,numTyres,color):
# self.numTyres = numTyres
# self.color = color
# def display(self):
# print(self.numTyres,self.color)
# print("I'm Lambo class's Display Function")
# class Car(Vehicle):
# def __init__(self,color):
# self.accelerator = True
# Vehicle.__init__(self,4,color)
# def drive(self):
# print("Driving")
# class Lambo:
# def __init__(self):
# Car.__init__(self, "Red")
# print("I'm Lamborgini")
# def drive(self):
# print("Lambo Driving")
# lamborgini = Lambo()
# lamborgini.drive()
# print(lamborgini.accelerator)
# lamborgini.display()
# # print(lamborgini.color)


# class Animal:
# # def __init__(self):
# # print("I'm a animal")
# def legs(self):
# print("It has Legs")
# def run(self):
# print("Runnning!")
# class Snake():
# def __init__(self):
# print("Hi i'm a snake")
# def eat(self):
# print("Eating")
#
# class Snail(Animal,Snake): #Method Resolution Order :- Left to Right
# def __init__(self):
# super().__init__()
# print("I'm a Snail")
# def bodyType(self):
# print("Im sticky")
# def eat(self):
# print("I'm Eating")
# def run(self): #Method OverRiding
# print("Crawling")
#
#
# s = Snail()




##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.#
#One Entity Many Forms
#
# #Functiion Polymorphism
# class Tata():
# def type(self):
# print("Truck")
# def color(self):
# print("Red")
#
# class Mahindra():
# def type(self):
# print("Car")
# def color(self):
# print("Black")
# def func(obj):
# obj.type()
# obj.color()
#
# obj_tata = Tata()
# obj_mahindra = Mahindra()
# func(obj_tata)
# print("--------")
# func(obj_mahindra)

# #Polymorphism in class
# class Truck:
# def capacity(self):
# print("50,000L")
# def color(self):
# print("Red")
# class Car:
# def capacity(self):
# print("7 seater")
# def color(self):
# print("Black")
#
# obj_truck= Truck()
# obj_car = Car()
# for vehicle in (obj_truck,obj_car):
# vehicle.capacity()
# vehicle.color()
# print("-----")


# #Polymorphism in Inheritence
#
# class Vehicle:
# def intro(self):
# print("We have differnet Vehicles")
# def speed(self):
# print("they have variation")
#
# class Truck(Vehicle):
# def speed(self):#Method OverRiding
# print("They are slow")
#
# class Car(Vehicle):
# def speed(self):
# print("They are faster")
#
# obj_veh = Vehicle()
# obj_tru = Truck()
# obj_car = Car()
#
# obj_veh.intro()
# obj_veh.speed()
# print("-----------")
#
# obj_tru.intro()
# obj_tru.speed()
# print("-----------")
#
# obj_car.intro()
# obj_car.speed()
# print("-----------")



# #Duck Typing
# class Duck:
# def Walk(self):
# print("Thapak Thapak")
#
# class Horse:
# def Walk(self):
# print("Tabdak tabdak")
# class Cat:
# def Talk(self):
# print("Meow... Walk..")
# def myfucntion(obj):
# #Put some condition here to check whether walk method is there in object or not
# if hasattr(obj,'Walk'):
# obj.Walk()
# if hasattr(obj,'Talk'):
# obj.Talk()
# d = Duck()
# h = Horse()
# c = Cat()
# myfucntion(d)
# myfucntion(h)
# myfucntion(c)

## Problem 1.
# class Duck:
# def sound(self):
# print("Quack Quack")
# class Dog:
# def sound(self):
# print("Woof Woof")
# class Cat:
# def __init__(self):
# self.sound = "Meow Meow"
#
# def allSound(obj):
# if hasattr(obj,'sound') and callable(obj.sound):
# obj.sound()
# dc = Duck()
# c = Cat()
# d = Dog()
# allSound(dc)
# allSound(c)
# allSound(d)


##Operator Overloading in Python##
# print(1+2)
# print("Coding" + "Deepak")
# print(3*4)
# print("Hello "*4)
# class ComplexNumber:
# def __init__(self,real,imaginary):
# self.real = real
# self.imaginary = imaginary
# complex_number1 = ComplexNumber(1,2)
# complex_number2 = ComplexNumber(3,4)
# # print(complex_number1 + complex_number2)#it shows an error TypeError: unsupported operand type(s) for +: 'ComplexNumber' and 'ComplexNumber'
# a = [1,2,3]
# b = [4,5,6]
# print(a+b)

#Magic Methods IN Python
# __str__()
# __add__()


#overloading of < opearator
# class ComplexNumber:
# def __init__(self,real,imaginary):
# self.real = real
# self.imaginary = imaginary
# def __lt__(self,complex_number_2):
# if self.real < complex_number_2.real:
# return True
# elif self.real == complex_number_2.real:
# if self.imaginary < complex_number_2.imaginary:
# return True
# else:
# return False
# else:
# return False
# def __str__(self):
# return str(self.real) + ' + ' + str(self.imaginary) + 'i'
#
# complex_number1 = ComplexNumber(1,2)
# complex_number2 = ComplexNumber(3,4)
#
# if complex_number1<complex_number2:
# print(f"Complex Number : {complex_number1} is less than the complex Number : {complex_number2}")
# else:
# print(f"Complex Number : {complex_number1} is not less than the complex Number : {complex_number2}")


# overloading the + Opearator
# class ComplexNumber:
# def __init__(self,real,imaginary):
# self.real = real
# self.imaginary = imaginary
# def __add__(self,other_complex_number):
# real_result = self.real + other_complex_number.real
# imaginary_result = self.imaginary + other_complex_number.imaginary
# return ComplexNumber(real_result,imaginary_result)
# def __str__(self):
# return str(self.real) + ' + ' + str(self.imaginary) + 'i'
#
# complex_number1 = ComplexNumber(1,2)
# complex_number2 = ComplexNumber(3,4)
#
# print(f"The sum of two complex Number is {complex_number1+complex_number2}")


# #Overloading comparison Operator !=, >, >=, <=
# class ComplexNumber:
# def __init__(self,real,imaginary):
# self.real = real
# self.imaginary = imaginary
# def __str__(self):
# return str(self.real) + ' + ' + str(self.imaginary) + 'i'
# def __gt__(self,other_complex_number):
# if self.real > other_complex_number.real:
# return True
# elif self.real == other_complex_number.real:
# if self.imaginary > other_complex_number.imaginary:
# return True
# else:
# return False
# else:
# return False
#
# def __ne__(self,other_complex_number):
# if self.real != other_complex_number.real:
# return True
# elif self.real == other_complex_number.real:
# if self.imaginary != other_complex_number.imaginary:
# return True
# else:
# return False
# else:
# return False
# def __le__(self,other_complex_number):
# if self.real <= other_complex_number.real:
# return True
# elif self.real == other_complex_number.real:
# if self.imaginary <= other_complex_number.imaginary:
# return True
# else:
# return False
# else:
# return False
# def __ge__(self,other_complex_number):
# if self.real >= other_complex_number.real:
# return True
# elif self.real == other_complex_number.real:
# if self.imaginary >= other_complex_number.imaginary:
# return True
# else:
# return False
# else:
# return False
#
# complex_number1 = ComplexNumber(1,2)
# complex_number2 = ComplexNumber(3,4)
#
# if complex_number1>complex_number2:
# print(f"Complex Number : {complex_number1} is Greater than the complex Number : {complex_number2}")
# if complex_number1!=complex_number2:
# print(f"Complex Number : {complex_number1} is Not Equals to complex Number : {complex_number2}")
# if complex_number1>=complex_number2:
# print(f"Complex Number : {complex_number1} is Greater than equals to the complex Number : {complex_number2}")
# if complex_number1<=complex_number2:
# print(f"Complex Number : {complex_number1} is less than equals to the complex Number : {complex_number2}")



##Abstract Class & Abstract Methods###
# ---------------------------------------------
from abc import ABC, abstractmethod
# class Animal(ABC):#now this is a abstract method
# @abstractmethod #now this is a abstract method
# def do(self):
# pass
# # print("Running......")
# class Dog(Animal):
# # pass #TypeError: Can't instantiate abstract class Dog with abstract method do
# def do(self):
# print("Barking")
#
# dog = Dog()
# dog.do()

# # example2:
# class Employee(ABC):
# def __init__(self,first_name, last_name):
# self.first_name = first_name
# self.last_name = last_name
#
# @property
# def full_name(self):
# return f"{self.first_name} {self.last_name}"
# @abstractmethod
# def calc_salary(self):
# pass
#
# class FullTimeEmployee(Employee):
# def __init__(self,first_name, last_name,salary):
# super().__init__(first_name,last_name)
# self.salary = salary
# def calc_salary(self):
# return self.salary
#
# class hourlyEmployee(Employee):
# def __init__(self,first_name, last_name, hours, rate):
# super().__init__(first_name,last_name)
# self.hours = hours
# self.rate = rate
#
# def calc_salary(self):
# return self.hours * self.rate
#
# class PayoutProcess:
# def __init__(self):
# self.employee_list = []
# def add(self,employee):
# self.employee_list.append(employee)
# def show(self):
# for i in self.employee_list:
# print(f"{i.full_name} \t ${i.calc_salary()} ")
#
# payout = PayoutProcess()
# payout.add(FullTimeEmployee('John','Deep',7000))
# payout.add(FullTimeEmployee('deepak','xc',9000))
# payout.add(FullTimeEmployee('ankit','de',900))
# payout.add(hourlyEmployee("Shruti","Yadav",150,60))
# payout.show()



##Exception Handling in Python##
# x =5
# y = 0
# print(x/y)#thsi shows an error due to an exception

# try:
# a = b
# # except:
# # a =5
# # print("Passed 5 to a")
# except Exception as e:
# print(e)#printing which typeof excepion occurs
#
# try:
# a = 15
# if a > 10:
# print(a/0)
# else:
# a = b
# except ZeroDivisionError:
# print("Can't divide by zero")
# print(a)
# except NameError:
# print("B is not defined")
# except:
# print("Don't Know")

# x = 10
# assert x == 5 #Assertion Error

# try:
# x = 10
# raise NameError("Name is Wrong") #Creating my own exception using raise
# except AssertionError:
# print("Assertion Failed")

# # Try Except Else Finally
# class AgeError(Exception):
# pass
# try:
# age = int(input("whats you age : "))
# if age <= 18:
# raise AgeError
# except AgeError as e: #Handle Exception
# print("Age CAn't be less than or equals to 18")
# else: #Runs if no Exception occurs
# print("Allowed")
# finally:#Executes every time
# print("Done with the example")



##Multithreading In Python##
# import threading
# def hello(name):
# print("Hi",name)
# def bye(name):
# print(f"{name} Bye!")
#
# if __name__ == "__main__":
# #create threads for a particular functon
# t1 = threading.Thread(target=hello,args=("Deepak",))
# t2 = threading.Thread(target=bye,args=("Deepak",))
#
# #start a therea
# t1.start()
# t2.start()
#
# # wait till therad 1 is completed
# t1.join()
# t2.join()
#
# print("Done")

# import threading
# import os
#
# def hello():
# print(f"Name: {threading.current_thread().name}")
# print(f"PID : {os.getpid()}")
#
# if __name__ == "__main__":
#
# #print pid of process
# print(f"Process PID : {os.getpid()}")
#
# #print the name of process
# print(f"Process Name : {threading.current_thread().name}")
#
# ##create the threads
# t1 = threading.Thread(target=hello,name="T1")
# t2 = threading.Thread(target=hello,name="T2")
#
# #Start the Threads
# t1.start()
# t2.start()
#
# #Wait the exeution of all threads
# t1.join()
# t2.join()
#
# print("Done!")

# #implementing Synchronization in multi threading
# import threading
#
# #global var
# x = 0
#
# def inc():
# global x
# x += 1
# def thread_task(lock):
# for i in range(100000):
# lock.acquire()
# inc()
# lock.release()
#
# def fun():
# global x
# #create a lock instance
# lock = threading.Lock()
# #Create Threads
# t1 = threading.Thread(target=thread_task,args=(lock,))
# t2 = threading.Thread(target=thread_task,args=(lock,))
#
# t1.start()
# t2.start()
#
# t1.join()
# t2.join()
#
# if __name__ == "__main__":
# for i in range(10):
# fun()
# print(f"Iteration: {i}, X : {x}")



##File Handling IN Python###
import os
# file = open("demofile.txt","r")
# print(file.read())
# print(file.readline())
# print(file.readline())
# print(file.readlines())
# for line in file.readlines():
# print(line)
# for line in file:
# print(line)
#
# #Close the file
# file.close()

#Writing to a file
# # a - append - will append to the end of the file
# # w - write - will overwrite any existing content
# file = open("demofile.txt","w")
#
# file.write("\nHi, There")
# file.close()
#
# file = open("demofile.txt","r")
# print(file.read())
# file.close()

#Creating a file using Python
# x - Create - willl create a file, returns an errror if the file exist
# a and w are same but doesnot give you an eror
# file = open("demofile1.txt","w")
# file.write("Hello World")
# file.close()
# file = open("demofile1.txt","r")
# print(file.read())
# file.close()

# #Deleting a File using Python
# # os.remove(filename) - to remove the file
# if os.path.exists("demofile.txt"):
# os.remove('demofile.txt')
# else:
# print("File doesn't exist")



##Functions & Methods in Python##
#Methods
# class Animal():
# def prop(self):
# print("I am a animal!")
#
# panda = Animal()
# panda.prop()

#Functions
# def add(x,y,c):
# sum = x + y + c
# print(sum)
# print(add(2,58,8))

# 1. User Defined Functions
# 2. Built in Functions
# 3. Lambda Functions
# 4. Recursive Functions

# # Lambda Functions
# m = lambda x,y,z : x+y+z
# print(m(4,5,6))

# ##Recursive Functions
# def Fact(n):
# if n == 0:
# return 1
# return n*Fact(n-1)
#
# print(Fact(4))


#Top Functions and methods in Interview Questions#
#Sort 0 1 2
# def count(arr,n):
# cnt0 = 0
# cnt1 = 0
# cnt2 = 0
#
# for i in range(n):
# if arr[i] == 0:
# cnt0+=1
# elif arr[i] == 1:
# cnt1+=1
# else:
# cnt2+=2
# arr.sort()
# # i = 0
# # while cnt0 > 0:
# # arr[i] = 0
# # cnt0 -= 1
# # i+=1
# # while cnt1 > 0:
# # arr[i] = 1
# # cnt1-= 1
# # i+=1
# # while cnt2 > 0:
# # arr[i] = 2
# # cnt2 -= 1
# # i+=1
# arr = [1,1,2,1,0,0,0,2,1]
# n = len(arr)
# count(arr,n)
# print(arr)
# # print(arr.count(1))

0 Comments