Posts

Showing posts from May, 2021

Class methods as alternative constructor

class Employee: no_of_leaves = 8 def __init__ ( self , aname , asalary , arole): self .name = aname self .salary = asalary self .role = arole @classmethod def from_str ( cls , string): '''params=string.split("-") return cls(params[0],params[1],params[2])''' return cls (*string.split( "-" )) karan = Employee.from_str( "karan-25000-datascientist" ) print (karan.salary)

Abstract base class & @abstractmethod

from abc import ABCMeta , abstractmethod # abstract base class # In this class u cannot make objects class shape( metaclass =ABCMeta): def printarea ( self ): return 0 class rectangle(shape): type = "rectangle" sides = 4 def __init__ ( self ): self .length = 6 self .breadth = 7 def printarea ( self ): return self .length * self .breadth rect1 = rectangle() print (rect1.printarea())

Multilevel inheritance

class dad: basketball = 1 class son(dad): basketball = 9 dance = 1 def isdance ( self ): return f"yea i dance { self .dance } no if times" class grandson(son): dance = 6 # def isdance(self): # return f"jackson can dance very awesomly {self.dance} no of times" darry = dad() larry = son() harry = grandson() print (harry.isdance()) print (harry.basketball)

Multiple inheritance

class Employee: var = 8 no_of_leaves = 8 def __init__ ( self , aname , asalary , arole): self .name = aname self .salary = asalary self .role = arole def printdetails ( self ): return f"name is { self .name } salary is { self .salary } role is { self .role } " @classmethod def change_leave ( cls , newleave): cls .no_of_leaves = newleave class player: var = 9 no_of_game = 4 def __init__ ( self , aname , agame): self .name = aname self .game = agame def printdetails ( self ): return ( f"the name is { self .name } game is { self .game } " ) class coolprogrammer(Employee , player): var = 10 language = "C++" def printlanguage ( self ): print ( self .language) harish = Employee( "harish" , 45000 , "front end" ) shiva = Employee( "shiva" , 50000 , "back end" ) virat = player( "virat" , [ ...

Single inheritance

class Employee: no_of_leaves = 8 def __init__ ( self , aname , asalary , arole): self .name = aname self .salary = asalary self .role = arole def empdetails ( self ): return f"name is { self .name } salary is { self .salary } role is { self .role } " @classmethod def change_leave ( cls , newleave): cls .no_of_leaves = newleave class programmer(Employee): def __init__ ( self , aname , asalary , arole , lang): self .name = aname self .salary = asalary self .role = arole self .language = lang def progdetails ( self ): return ( f"the programmer name is { self .name } salary is { self .salary } role is { self .role } language is { self .language } " ) harish = Employee( "harish" , 45000 , "front end" ) shiva = Employee( "shiva" , 50000 , "back end" ) raj = programmer( "raj" , 100000 , "data sci...

Public, protected & private

  # public- # protected- # private- class myclass: class_teacher = "sajita" # public _protected = "chocolate" # protected __private = "gf" # private def __init__ ( self , aname , aaim): self .name = aname self .aim = aaim student1 = myclass( "harish" , "software developer" ) print (student1._protected) print (student1._myclass__private) # the process of calling private value is called name mangling

Map filter & reduce

# -------------------MAP---------------------] '''numbers=["1","5","99","54"] numbers=list(map(int,numbers)) for i in range(len(numbers)): numbers[i]= int(numbers[i]) numbers[2]=numbers[2]+1 #print(numbers[2]) def sq(a): return (a*a) num=[2,4,5,77,100,34,3,45] square=list(map(sq,num)) print(square)''' '''num=[2,4,5,77,100,34,3,45] square=list(map(lambda x:x*x,num)) print(square)''' '''def square(a): return (a*a) def cube(a): return(a*a*a) func=[square,cube] for i in range(5): val=list(map(lambda x:x(i),func)) print(val)''' # -------------------FILTER---------------------- '''list_1=[1,2,3,4,5,6,7,8,9] def is_greater_5(num): return num>5 is_greater_5=list(filter(is_greater_5,list_1)) print(is_greater_5)''' # -------------------REDUCE-------------------- '''list1=[2,3,4,5] num=0 for i in list1: num+=i print(num)...

Lambda or anonymous function

#lambda is another way to make function def add (a , b): return a+b minus= lambda x , y : x-y #we made a function using lambda. def minus (x , y): #we made this function without lambda but both are same return x-y print (minus( 5 , 2 ))

Operator overloading & dunder method

Image
'''Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading. ''' class myclass: class_teacher = "sajita" def __init__ ( self , aname , aage): # dunder method self .name = aname self .age = aage def printdetails (): return ( f"my name is { self.name } my age is { self.age } " ) def __add__ ( self , other): # dunder method return self .age + other.age def __truediv__ ( self , other): # dunder method return self .age / other.age def __repr__ ( self ): return ( f"myclass(' { self .name } ...

Diamond problem in multiple inheritance

class A: def met ( self ): print ( "this is a method in class A" ) class B(A): def met ( self ): print ( "this is a method in class B" ) class C(A): def met ( self ): print ( "this is a method in class C" ) class D(B , C): def met ( self ): print ( "this is a method in class D" ) a = A() b = B() c = C() d = D() d.met()

Join() function

lis=[ "sarah" , "jossie" , "vivi" , "preeti" , "soundariya" , "rakul" ] for item in lis: print (item , "and" , end = " " ) print ( "other my gfs" ) #this code result is same as upper code but in this we had used join function which make easy to code. a= " and " .join(lis) print (a , "other ex gfs" )

Global variable & keyword

l= 10 #Global variable def function1 (n): m= 8 #local variable print (n , "this is printed" ) global l #used to change global variable in local area l=l+ 5 # l=5 #local variable print (l , m) function1( "this is me" ) print (l) #print(m) l= 10 #global variable def function1 (n): #l=5#local var global l #this is global keyword which give permission to change the global var in local area l= 100 a= 6 #local var print (l , a) l=l+ 5 print (n , "Iwas born on 26 jan 2002" ) function1( "my name is N harish," ) print (l) def harish (): #this is for more understanding k= 20 def shiva (): global k k= 5 print (k) shiva() print (k) harish()

Function & docstring

e= 4 f= 5 c= sum ((e , f)) #built in function print (c) def function1 (a , b): print ( "now iam in function" , a+b) function1( 5 , 10 ) def function2 (c , d): """this is a function which will calculate average of two no""" average=(c+d)/ 2 #print (average) return average '''v=function2(10,20) print(v)''' print (function2. __doc__ )

Overriding & super()

class a: classvar1 = "iam a class variable in class a " def __init__ ( self ): self .var1 = "iam inside class a constructor" self .classvar1 = " instance var in class a " class b(a): classvar1 = "iam in class b" def __init__ ( self ): self .var1 = "iam inside class b constructor" self .classvar1 = " instance var in class b" super (). __init__ () # it is used to access the parent class constuctor because when we override something previous one will not run print ( super ().classvar1) a1 = a() b1 = b() print (b1.classvar1)

Polymorphism

 #What is Polymorphism :  #The word polymorphism means having many forms. In programming, polymorphism means same function name (but different signatures) being uses for different types. print(5+6) print("5"+"6")

File read, write, & append

#this is used to write sth in a file but previous content will be delete f= open ( "harish" , "w" ) f.write( "harish is good boy " ) f.close() #this is used to add sth in a file at end but in this previous content will not delete f= open ( "harish" , "a" ) f.write( "harish is goldenba \n " ) f.close() #in this we can find out how many charecters we add in file f= open ( "harish" , "a" ) a=f.write( "harish is goldenba \n " ) print (a) f.close() #this is used to read and write both f= open ( "harish" , "r+" ) print (f.read()) f.write( "well dude" )

fstrings

#F strings '''me="harish" a1=3 a="this is %s %s %s"%(me, a1,"hi") print(a)''' #in another way '''me="harish" a1= "joke" a="this is {1} {0} " b= a.format (me, a1) print (b)''' #another easy way me= "harish" a1= 4 a= f"this is { me } { a1 } " #here f is fast print (a)

class method

class myclass: class_teacher = "niraj sir" def __init__ ( self , name1 , roleno1 , aim1): self .name = name1 self .role_no = roleno1 self .aim = aim1 # u have to use decorator for using classmethod @classmethod # it works on class variables def setstream ( cls , stream): myclass.stream1 = stream myclass.setstream( "science" ) student1 = myclass( "harish" , 1 , "software engineer" ) student2 = myclass( "shiva" , 2 , "hacker" ) print (student2.stream1)

Self & __init__() constructor

# --------------self---------------- class class1: class_teacher = "niraj sir" def details ( self ): return f"my name is { self .name } my role no is { self .role_no } i want to become a { self .aim } " student1 = class1() student2 = class1() student1.name = "harish" student1.role_no = 1 student1.aim = "software engineer" student2.name = "shiva" student2.role_no = 2 student2.aim = "hacker" print (student1.details()) # ----------------__init__()----------- class class1: class_teacher = "niraj sir" def __init__ ( self , name1 , roleno1 , aim1): self .name = name1 self .role_no = roleno1 self .aim = aim1 student1 = class1( "harish" , 1 , "software engineer" ) student2 = class1( "shiva" , 2 , "hacker" ) print (student1. __dict__ ) print (student2.name)

Instance & class variables

class Employee: # class no_of_leaves = 8 # class variables #this will be same for all objects pass harish = Employee() # here harish and shiva are objects of class "Employee" harish.name = "harish" # instance variables harish.role = "front end" harish.salary = 45000 print (harish. __dict__ ) # this will show whole instance with value as a dictionary shiva = Employee() shiva.name = "shiva" shiva.role = "back end" shiva.salary = 50000 # u can access no_of_leaves with any objects, result will be same print (shiva.no_of_leaves) print (harish.no_of_leaves) # u can access from class also print (Employee.no_of_leaves) # u cannot change the value of no_of_leaves with objects..it is possible with only class that is Employee Employee.no_of_leaves = 10 print (Employee.no_of_leaves) print (Employee. __dict__ )

Classes

#classes - template #object - instance of the class #DRY - do not repeat yourself' class student: pass harish=student() virat=student() harish.name= "harish" harish.std= 12 harish.age= 19 harish.school= "jnv" virat.subject=[ "hindi" , "math" ] print (harish.name , virat.subject)

enumerate function

l1 = [ "potato" , "tomato" , "egg roll" , "chatpati" , "rice" ] i = 0 for item in l1: if i % 2 == 0 : print ( f"pls bring this items only { item } " ) i += 1 # this is short method of upper code using enumerate function for index , item in enumerate (l1): if index % 2 == 0 : print ( f"pls bring this item only { item } " )

different methods to read a python file

f = open ( "harish" , "r" ) print (f.readline()) # 1 method...it will show the content line by line print (f.readlines()) # 2 method...it will show the whole content not line by line for line in f: # 3 method print (line , end = "" ) content = f.read() # 4 method print (content)

*args and **kwargs

# def function_name_print (a,b,c,d,e): # print (a,b,c,d,e) def funargs (normal , *arg , **kwargs): # remembar always normal argument should at first otherwise it will give error # fist should be normal then args then ar last should be kwargs. # print (arg[0]) # print (type(arg)) print (normal) for item in arg: print (item) print ( "i would like to introduse some heros" ) for key , value in kwargs.items(): print ( f" { key } is a { value } " ) # function_name_print("harish","shankar","raju","rajesh","kutti") har = [ "harish" , "shankar" , "raju" , "rajesh" , "kutti" , "vijay" ] kw = { "harish" : "school leader" , "sawan" : "house leader" , "tushar" : "class leader" } normal = "iam a normal arguement" funargs(normal , *har , **kw)

using with block to open python file

with open ( "harish" ) as f: a=(f.readlines( 13 )) print (a) '''f=open("harish") content=f.read() print(content)'''