id
int64
0
25.6k
text
stringlengths
0
4.59k
4,400
(continued from previous page new radius radius +expansion day + increment the number of days by one print the data print(dayexpansionradius print the number of days print("number of days ="dayfollowing is the output for gold ringpython expansion py "gold dayexpansionradius formatted output in the below codethe 'formatoption of print statement is used to display the output in more readable form expansion py find the number of days when radius cm due to heat-expansion import sys if len(sys argv! display error message for missing arguments raise systemexit("usage ring py \"metal\radius" sys argv[ is the file name metal sys argv[ input is read as string therefore it is converted into float radius float(sys argv[ ] list of expansion rate for different metal rate [ [coppergoldiron day #use any of the below #below is not in good format print("{ }{ }{ }format("day""expansion""radius") #"right aligned"left aligned# string with width print("{:> {:> {:> }format("day""expansion""radius") #old style print("% % % ("day""expansion""radius") while radius multiply by correct expansion rate if metal ="copper"expansion radius rate[ elif metal ="gold"(continues on next page formatted output
4,401
(continued from previous page expansion radius rate[ elif metal ="iron"expansion radius rate[ elseprint("enter the correct metal"break new radius radius +expansion day + increment the number of days by one #print the data # digits # digits with decimal points print("{:> {:> {:> }format(dayexpansionradius) print the number of days print("number of days ="dayfollowing is the outputs of the print statementswhich looks better than the output in the previous sectionpython expansion py "gold day expansion radius saving results in file there are two ways to save the results in the file in the first methodwe can redirect the output of the print statement to the file (instead of printing then on the terminalnote that the '>sign will overwrite the file contentswhereas the '>>sign will append the content at the end of the file alsoplease see the unix guide to learn more commands like 'catwhich is used to display the content of the file python expansion py "gold data txt cat data txt day expansion radius python expansion py "gold >data txt cat data txt day expansion day expansion radius radius in the other methodwe can open the file in the python script and then save the data in the fileas shown below more file operations will be discussed in next notethis method is better than previous methodas we can select the outputs which should saving results in file
4,402
be written in the file for exampleline will not be printed in the fileif the wrong input values are provided during execution of the script expansion py find the number of days when radius cm due to heat-expansion import sys if len(sys argv! display error message for missing arguments raise systemexit("usage ring py \"metal\radius" sys argv[ is the file name metal sys argv[ input is read as string therefore it is converted into float radius float(sys argv[ ] list of expansion rate for different metal rate [ [coppergoldiron day out_file open("expansion txt"" "open file in write mode #use any of the below #below is not in good format print("{ }{ }{ }format("day""expansion""radius") #"right aligned"left aligned# string with width print("{:> {:> {:> }format("day""expansion""radius")file out_file #old style print("% % % ("day""expansion""radius") while radius multiply by correct expansion rate if metal ="copper"expansion radius rate[ elif metal ="gold"expansion radius rate[ elif metal ="iron"expansion radius rate[ elseprint("enter the correct metal"break new radius radius +expansion day + increment the number of days by one #print the data # digits # digits with decimal points print("{:> {:> {:> }format(dayexpansionradius)file out_file print the number of days print("number of days ="daynowexecute the script and see the content of the file as below saving results in file
4,403
python expansion py "gold cat expansion txt day expansion radius alter the printing sequence we can alter the printing location of the arguments as below{ }{ }{ are the position th argument 'daywill go in first position and so on print("{ }{ }{ }format("day""expansion""radius")same as above but with modified locations parameter ( daywill be printed at first position { print("{ }{ }{ }format("expansion""radius""day")same can be done with following formatting print("{:> {:> {:> }format("day""expansion""radius")same as abovebut location is defined print("{ :> { :> { :> }format("expansion""radius""day") conclusion in this we saw various print statements alsowe learn the methods by which can save the outputs in the file in the next we will learn some more file operations alter the printing sequence
4,404
csv module introduction in this we will see some of the features of the python in-built csv module this module can be quite useful for processing the files as shown in this basic file operations in this sectionwe will perform some operations on the file without using the csv module for this first create file 'price csvwith following contents in itdate,metal,radius,price,quantity "","gold", , , "","silver", , , "","iron", , , "","gold", , , "","copper", , , "","iron", , , open and close the files next go to the folderwhere the file 'price csvis saved and open python shell there and run the following commands open("price csv"' ' it is buffered text stream data read(read the buffer into data print(dataprint the data date,metal,radius,price,quantity "","gold", , , "","silver", , , "","iron", , , "","gold", , , "","copper", , , "","iron", , , we can access and print the individual lines as wellas shown belowr open('price csv'' 'open in read mode for line in (continues on next page
4,405
(continued from previous pageprint(linedate,metal,radius,price,quantity "","gold", , , "","silver", , , "","iron", , , "","gold", , , "","copper", , , "","iron", , , next close the file once the file is closed than we can not perform further operation on buffer close( close(for line in rfile is closedtherefore can not be accessed print(linetraceback (most recent call last)file ""line in valueerrori/ operation on closed file with open statement in this section'with openstatement is used to read the file notedo not forget to close the file using close(command furtherfile will be closed automaticallyif it is open using 'withstatementas shown in this section this method is quite useful when we write the codes in the filesinstead of python-shell in the below codethe file is open using 'withstatement therefore it will be closed as soon as the 'withstatement ends therefore buffer will not be accessible outside the 'withstatement for example in the below codeline generates the erroras buffer 'wis outside the 'withstatement with open('price csv'' 'as wdata read(print(dataprint the data date,metal,radius,price,quantity "","gold", , , "","silver", , , "","iron", , , "","gold", , , "","copper", , , "","iron", , , for lines in wfile is already closed (continues on next page basic file operations
4,406
(continued from previous page print(linestraceback (most recent call last)file ""line in valueerrori/ operation on closed file strings operations we need to perform string-operations to the data for the further processing the data extracting the lines which contains "goldetc in this sectionwe will see some of the string operations and the perform these operations on the file 'print csvm "hello worldprint(mhello world [ print first character 'hm[ : print first characters 'hem[- print last character 'dm[- :- print nd and rd last (but not the last'rlm[- :print last characters 'rldlets see some more string operations as below please read the comments in the codes commands strip(strip(''replace('''-'split(","description remove end line character remove replace with make list for data with separator ', open('price csv'' 'for line in fprint(linedate,metal,radius,price,quantity "","gold", , , "","silver", , , "","iron", , , "","gold", , , "","copper", , , "","iron", , , line loop store only one value (continues on next page strings operations
4,407
(continued from previous page'"","iron", , , \nremove the end line character \ line strip('"","iron", , , line strip operation does not save automatically '"","iron", , , \nline line strip(save the split operation line '"","iron", , , line replace('"''-'replace with '--,-iron-, , , create list and split at comma columns line split(','columns ['""''"iron"'' '' '' 'type(columnsacess columns columns[ '""remove from the data for icol in enumerate(columns)columns[icol strip('"'columns ['''iron'' '' '' 'columns[ 'all the items are stringtherefore multiplaction can not be performed total_price columns[ ]*columns[ traceback (most recent call last)file ""line in typeerrorcan' multiply sequence by non-int of type 'strconvert string to 'floatand multiple total_price float(columns[ ])*int(columns[ ]total_price perform calculations in this sectionwe will write python script which will use all the operations of the previous sectionto calculate the total cost of all the items price py total_price for all items in the list with open('price csv'' 'as fopen file in read mode header next(rowsskip line header for line in fline line strip(remove \ (continues on next page perform calculations
4,408
(continued from previous page columns line split(','split line on columns[ columns[ strip('"'remove for metal columns[ float(columns[ ]radius columns[ float(columns[ ]price columns[ int(columns[ ]quantity columns[ columns[ strip('"'date total_price +columns[ columns[ print("total price ="total_pricefollowing is the output of above listingpython price py total price importantnote that'next(rows)is used in listing which return the next row of the reader' iterable object as list sincethe first row is extracted and save in the headertherefore it will not be available inside the for loop problem with current method create file 'price csvwith following contents note that the contents of this file and the 'price csvare the same expect for the datewhich is different format date,metal,radius,price,quantity "jun ","gold", , , "jul ","silver", , , "jan ","iron", , , "mar ","gold", , , "sep ","copper", , , "jan ","iron", , , now read the file 'price csvin 'price pyas below price py total_price for all items in the list with open('price csv'' 'as fopen file in read mode header next(rowsskip line header for line in fline line strip(remove \ columns line split(','split line on columns[ columns[ strip('"'date columns[ columns[ strip('"'remove for metal columns[ float(columns[ ]radius columns[ float(columns[ ]price columns[ int(columns[ ]quantity total_price +columns[ columns[ print("total price % total_pricenext execute the code and following error will be generated problem with current method
4,409
python - price py traceback (most recent call last)file "price py"line in columns[ float(columns[ ]radius valueerrorcould not convert string to float'"gold"this error is generated because the date has one commabecause of which an additional column is added to the listas shown belowcolumns ['jun ' ''"gold"'' '' '' 'noteone way to remove this problem is to redesign the code according to new date format note thatthe dates are in standard formats in both the cases therefore we should think like this"this is not new problem as everything is in standard formattherefore there must be an standard way to solve this problemand look for the standard library or third party packages to solve the problem currentlywe can solve this problem using csv moduleor we can use pandas-library which is quite powerful to solve the problems in data-processing click here to learn the pandas csv module in this sectionwe will see two functionalities of the csv module 'csv readerand 'csv dictreadercsv reader before modifying the python scriptlet us see the functionality of the csv module note thatin the below outputsthe stripping and splitting operations are performed by the csv module itself import csv open('price csv'' 'rows csv reader(fread the file using csv for row in rowsprint(row['date''metal''radius''price''quantity'['jun ''gold'' '' '' '['jul ''silver'' '' '' '['jan ''iron'' '' '' '['mar ''gold'' '' '' '['sep ''copper'' '' '' '['jan ''iron'' '' '' 'following is the python script which can perform the calculation on both the files 'price csvand 'price csvlisting price calculation using csv module price py import csv total_price for all items in the list with open('price csv'' 'as fopen file in read mode rows csv reader(fheader next(rowsskip line header (continues on next page csv module
4,410
(continued from previous pagefor row in rowsrow[ float(row[ ]price row[ int(row[ ]quantity total_price +row[ row[ print("total price % total_pricerun the above script and we will get the following outputpython price py total price importantnote thatwhen we use standard library then lots of task are reduced here we need not to perform any cleaning operation removing double-quotes and commas etc alsothe code is shorter and cleaner when we used the csv module csv dictreader the dictreaderoption is same as the reader'but it maps the information into the dictionarywhich enhances the data processing capabilities notereaderreturns reader-object which iterates over the line of the csv file dictreaderis similar to readerbut maps the information in the dictionary in the below examplepython data structure are usede list and set etc which are discussed in next furtherwe will some more examples of dictreaderafter learning the 'data structureand 'functionsimport csv list(csv dictreader(open('price csv'))read dictreader in list [ first item in the list ordereddict([('date''')('metal''gold')('radius'' ')('price'' ')('quantity'' ')][row['metal'for row in fdisplay all values list ['gold''silver''iron''gold''copper''iron'{row['metal'for row in fdisplay unique values set {'silver''copper''iron''gold' [row for row in if row['metal'='gold'read gold entries len(gtotal gold entries for item in gprint radiusprice and quantity print(item['radius']item['price']item['quantity'] csv module
4,411
conclusion in this we saw the various ways to read the files alsowe learn the usage of csv module lastlywe saw some of the data structure available in pythonwhich will be discussed in details after the next in the next we will discussed the "functionsand "error handling conclusion
4,412
functions docstring the content between the 'is known as 'docstring'which are displayed by the 'helpfunction as shown below press 'qto exit from help-screen def add num(xy)''add two numbers xy ''print( +yadd num( help(add numhelp on function add num in module __main__add num(xyadd two numbers xy types of docstring there are two standard format of creating the docstringsi numpy style and goole stylewhich are supported by sphinx-documentation for generating the auto-documentation of the project convert previous code into function conversion nowwe will convert the code in listing into function conversion process is quite simpleas shown in listing where function with docstring is defined at lines - ther previous code is indented and finally return statement is added in line lines - calls the function and print the output lastlylines - are the standard boilerplate to set the function 'mainas the entry point listing price calculation using function price py import csv def ring_cost(filename)(continues on next page
4,413
(continued from previous page ''calculate the total cost '' total_price for all items in the list with open(filename' 'as fopen file in read mode rows csv reader(fheader next(rowsskip line header for row in rowsrow[ float(row[ ]price row[ int(row[ ]quantity total_price +row[ row[ print("total price % ftotal_pricereturn total_price return total_price def main()total ring_cost('price csv'function call print("total price % totalprint value standard boilerplate main is the starting function if __name__ ='__main__'main(python price py total price debugging in listing we have to manually change the file name in the 'price pyfilewhereas in listing we can pass the filename as the parameter in the section as shown belowpython - price py total price ring_cost('price csv' ring_cost('price csv' notein the above command'python - price py'the main(function is called and after entering the python shellwe can call the function directly ring_cost('price csv')and the corresponding 'return value' will be printed in the shell glob module 'globmodule can be used to select the files for further processingas shown in this section to understand itfirst create some files as belowtouch data txt data txt data txt data_ txt data_ txt data_ txt data csv data csv data csv nextopen the python shell and see the following function of 'globmodule glob module
4,414
glob glob('csv'find all csv files ['data csv''data csv''data csv'glob glob('datatxt'select all txt file which starts with 'data['data_ txt''data_ txt''data txt''data_ txt''data txt''data txt'select txt files which have one character between 'dataand txtglob glob('datatxt'['data txt''data txt''data txt'glob glob('data[ - ]csv'select csv file with numbers , , after 'data['data csv''data csv'notethe 'globmodule returns the 'listthe list is in unordered form price calculation on files using 'globnowwe will use the glob module to perform 'price calculationon files using 'globmodule first open the python shell without using '-ioperation python since we did not use the '-ioperation to open the shelltherefore we need to import the function 'ring_costin the shellas shown belowimport glob from price import ring_cost files glob glob('pricsv'for file in filesprint(filering_cost(file)price csv price csv warningnote that we need to restart python shell every timewe made some changes in the code this is required as the 'importstatement loads all the data at the first timeand when we re-import the modules then it is fetched from the cache note thatthe 'globreturns listtherefore we can extend the list using various listing operation this can be useful when we have files names with different namesbut required same operations we want to perform price calculation on another set of items which has same columns as price csv file list can be modified as belowfiles glob glob('pricsv'files glob glob('pricsv'files extend(files extend list files ['price csv''price csv''price csv''price csv'files append('price csv'append data files ['price csv''price csv''price csv''price csv''price csv' glob module
4,415
data types and objects introduction in this we will see various data types available in the python alsowe will use these data types for processing the data (also known as data miningeverything in python is the object builtin types numbersstringslistset and dictionary etc are objects furtheruser define objects can be created using 'classesthis describes the working of python object model along with builtin data types notethis contains lots of details about the data objects and data types we can skip this at this momentexcept section and reference back to itwhenever required identity and type each object has an identity in the form of integer and type the identity corresponds to the location of the object in the memory id(xid is unique memory address type(xtype of class is 'typeclass circle(object)pass id(circle type(circletype of builtin-type is 'typetype(int
4,416
notethe type of classes and builtin types int and float are type as shown in above code 'isoperator the 'isoperator is used to compare the identity of two objectsa [ is new name for and have same id id( id( since and are samehence if modify ba also changes append( [ 'isreturns true if 'idis same is true is true comparing objects objects can be compared based on valuesid and types as shown belowdef compare(ab)if is bprint(objects have same id"if =bprint(values of objects are same"if type(ais type( )print(types of objects are same" =[ =[ id( id( compare(xyvalues of objects are same types of objects are same compare( objects have same id values of objects are same types of objects are same (continues on next page identity and type
4,417
(continued from previous pagecompare( types of objects are same compare(xyobjects have same id values of objects are same types of objects are same id( id( isinstance notethe type of an object is itself an objectwhich is known as object' class this object ( object' classis unique for given typehence can be compared using 'isopeartor as shown belowx [ [ if type(xis listx append(yx [ [ ]above operation can be performed using isinstance(objecttypeas shown belowx [ [ if isinstance(xlist) append(yx [ [ ] reference count and garbage collection all the objects are reference counted this reference count is increased whenever new name is assigned to object or placed in container listtuple or dictionary etc getrefcount getrefcount can be used to see the reference count of an object import sys sys getrefcount( (continues on next page reference count and garbage collection
4,418
(continued from previous pagesys getrefcount( [ append(rc [ sys getrefcount( garbage collection the 'delcommand decrease the value of reference countwhen this value reaches to zerothe object is garbage collected as shown belowdel sys getrefcount( del sys getrefcount( del shallow and deep copy notein section we assigned awhich created reference for as howeverthis behaviour is quite different for mutuable objects list and dictionary there are two types of reference for these cases shallow copy and deep copy shallow copy in shallow referenceinner list or dictionary shared the data between two references as shown below note thata and are not same ' is bresults as falsebut still change in results in change in [ [ ] list(acreate shallow copy [ are still shared [ [ ] is false append( no change in [ [ ] [ ][ value of is changed [ [ ] reference count and garbage collection
4,419
deep copy above problem can be solved using 'deep copydeep copy creates new object and recursively copies all the objects it contains import copy [ [ ] copy deepcopy(aa is false [ ][ ]= [ [ ] is not changed [ [ ] first class object all objects in python are said to be 'first classi all objects that can be named by an identifier have equal status in below code'tyis assigned the object 'str'now 'tycan be used in place of str as shown belowty=str ty int ty(' ' this feature is quite useful for writing compact and flexible code in below codelist comprehension is used to change the data type of 'stock'herestock is stringwe want to split it and convert the data in to correct format stringint and float stock "goog field_types [strintfloatsplit_stock stock split(','split data and get list split_stock ['goog' ' 'change the format stock_format [ty(valfor tyval in zip(field_typessplit_stock)stock_format format [strintfloat['goog' builtin types for representing data there are various types of data typeswhich can be divided as shown in table first class object
4,420
table builtin datatypes category type name description none nonetype none numbers int integer float floating point complex complex number boolean true or false sequences str character string list list tuple tuple mapping dict dictionary sets set mutable set frozenset immutable set none none object is usually used with the function for setting default value for the kwargs def add( =noneb=noneetc furtherif none is return by function than it is considered as 'falsein boolean expressionsx none type(xinput arguments values as none def add num( =noneb=none) print(creturn none add num( none is return type(snone is considered as false if sprint(" has some value"elseprint(" is none" is none isinstance can not be used with none typeisinstance(xnonetraceback (most recent call last)file ""line in typeerrorisinstance(arg must be type or tuple of types numbers complex numbers are represented as pair of two floating-point number real part and complex part of complex number can be extracted as below builtin types for representing data
4,421
real imag conjugate(( - jsequences sequences are the set objects which are indexed by non-negative integers python has three types of sequences stringlist and tuple strings and tuples are immutable objectswhereas list is mutable object table shows the operations which are applicable to all the sequencesoperation [is[ :js[ : :stridelen(smin(smax(ssum(ssum( [initial]all(sany(stable common operations to all sequences description example [ returns element [ returns slice [ : [ returns extended slice [ : : [ number of elements len( mininum value in min( maximum value in max( sum of all elements sum( sum of elements initial value sum( return trueif all true in return trunif any true in 'alland 'anyexample ( tuple [ : ( trueas all items in are greater than zero all(item> for item in xtrue falseas all items in are not greater than all(item> for item in xfalse trueas some items in are greater than any(item> for item in xtrue some string operations are shown belows 'meher krishna patels[: to 'mehers[:- to sixth last (continues on next page builtin types for representing data
4,422
(continued from previous page'meher krishna [- :'patelfifth last to end table shows the operations which are applicable to mutable sequences onlyi string and listtable operations for mutuable sequences only item description [iv item assignmentv value [ijt slice assignmentt tuple/list [ : :stridet extended slice assignment del [iitem deletion del [ :jslice deletion del [ : :strideextended slice deletion some of the operations of table are shown belowx [ [ value assignment [ [ : - - - slice assignment [ - - - [ : [- - - [ - - - - [ : : extended slice assignment [ - - - del [ : slice deletion [ - - list list is the mutable sequenceswhich is often used to store the data of same type it can be seen as the columns of spreadsheet notelist(scommand converts any iterable to list if iterable is already listthen list(scommand will create new list with shallow copy of 'sas discussed in section table shows various methods supported by list object builtin types for representing data
4,423
table list methods method list(ss append(xs extend(xs count(xs index( [start [stop]] insert(ixs pop([ ] remove(xs reverse( sort([key [reverse]description convert to list append element xto the end of append new list xto the end of count occurances of in return the smallest where [ = start and stop optionally specify the starting and ending for the search insert at index pops the element index if 'iis ommited then last value popped out search for first occurrence of and remove it reverse the order of list sorts item fo 'keyand 'reverseshould be provided as keywords some of the examples of commands in table are listed belows [ append( [ append([ ] [ [ ] [ extend([ ] [ count( index( insert( - [ - pop( [ - pop( - [ remove( [ reverse( [ note' sort()method sorts and modifies the original listwhereas 'sorted()option sorts the contents of the listbut does not modify the original listtherefore we need to save it manuall furtherif we try to save the outcome of sort(in some other listit will not work as shown below builtin types for representing data
4,424
name_age ['tom' ]['jerry' ]['pluto' name_age [['tom' ]['jerry' ]['pluto' ]name_age sort(key=lambda namename[ ]sort by name name_age [['jerry' ]['pluto' ]['tom' ]name_age sort(key=lambda ageage[ ]name_age [['jerry' ]['tom' ]['pluto' ] [ name_age sort(key=lambda ageage[ ] nothing is saved in sort by age can not save the output use sorted(to save outputs to another list sorted(name_agekey=lambda ageage[ ]sorted(by age [['jerry' ]['tom' ]['pluto' ] sorted(name_agekey=lambda namename[ ] [['jerry' ]['tom' ]['pluto' ]sorted(by name strings various strings methods are shown in table as oppose to list methodsstring methods do not modify the underlying string data in the other wordsthe string methods return the new string which can be saved in new string object builtin types for representing data
4,425
table string methods method capitalize( center(width[,pad] count(sub[start [end]] endswith(suffix[start [end]] expandtabs([tabsize] find(sub [start [end]] rfind(sub [start [end]] format(args*kwargss index(sub[start [end]] rindex(sub[start [end]] isalnum( isalpha( isdigit( islower( isspace( istitle( isupper( join(ts ljust(width [fill] rjust(width [fill] lower( upper( lstrip([chrs] partition(seps partition(seps replace(oldnew [maxreplace] split([sep [maxsplit]] rsplit([sep[,maxsplit]] splitlines([keepends] startswith(prefix[,start [,end]] strip([chars] rstrip([chars] swapcase( title( zfill(widthdescription capitalize the first letter centers the string in field of length width pad is padding character counts occurrence of the specified substring sub checks for the end for suffix replace tabs with spaces find the first occurrence of substring sub find last occurrence of substring sub format string find the first occurrence of sub find the last occurrence of sub checks whether all characters are alphanumerics checks whether all characters are alphabets checks whether all characters are digits checks whether all characters are lowercase checks whether all characters are spaces checks whether all characters are titlecased checks whether all characters are uppercase joins string in sequence with as separator left or right align in string of size 'widthchange string to lower or upper case remove leading white space or [chrsif provided partitions string based on seperator string 'sepit returns tuple (headseptailor ( """"if seperator is not provided partitions string but search from the last replace substring splits string using 'sepas delimiter maxsplit is the maximum number of split is used for checking from the end splits the string into list of line if keepends is then trailing newlines are preserved checks whether string starts with prefix removes leading and trailing white spaces or chars if provided changes the case of string return title-case version of string pads string with zeros on the left up to specified width some of the examples of commands in table are listed belows "meher krishna patels capitalize('meher krishna patels center( meher krishna patel center( meher krishna patel (continues on next page builtin types for representing data
4,426
(continued from previous pages center( '#''#####meher krishna patel###### count(' ' count('eh' endswith('patel'false endswith('patel 'space added at the end false endswith('er' mehercheck from to true '{}{}{}format(' '' '' ''abc'{ }{ }{ }format(' '' '' ''cab'{name}{age}format(name='meher'age= 'meher keywords index(' ' index(' ' space seperator join( ' lname #mehername lstrip('#mehername lstrip(lstrip('##'mehers partition('('meher'''krishna patel' partition('krishna'('meher ''krishna'patel' replace(' '' ''meher krishna patels replace(' '' ' 'meher krishna patels split('['meher''krishna''patel' 'my name is meher \nwhat is your name?(continues on next page builtin types for representing data
4,427
(continued from previous pageprint(lmy name is meher what is your namel splitlines(['my name is meher ''what is your name?' splitlines( ['my name is meher \ ''what is your name?' #meher krishna pateln strip('#meher krishna patel# strip(strip('#''meher krishna patels zfill( ' meher krishna patelmapping types mapping object represents an arbitrary collection of objects that are indexed by another collection of arbitrary key values unlike sequencesa mapping object can be indexed by numbersstrings and other objects furtherthe mappings are mutable dictionaries are the only builtin mapping types in python table shows the list of various dictionary operationsitem len(mm[kdel [kk in clear( copy( fromkeys( [,val] get[ [,msg] items( keys( values( pop( [,msg] popitem( setdefault( [, ] update(btable methods and operations on dictionariesdescription number of item in returns value of key delete key return true if key exist remove all item from make copy of create new dictionary with keys from sequnece 'noneor val (if providedis filled as values to all keys returns [ ]if not found return msg returns itemskeys or values these are return as iterator pops [kif foundotherwise shows msg if providedelse keyerror remove one key-value at random same as get(but set the key with value none/vif not found (instead of keyerroradd all objects of to some of the examples of commands in table are listed belowm 'name'aa''shares 'price len( ['name'(continues on next page builtin types for representing data
4,428
(continued from previous page'aam['name''googm['name''googdel ['shares'len( 'sharesin false 'namein true clear( { 'name'tiger''age {'name''tiger''age' copy( {'name''tiger''age' stock ['name''shares''price' ={ fromkeys(stock{'name'none'shares'none'price'nonen note that results are not stored in { ={ fromkeys(stock {'name' 'shares' 'price' get('name' get('rise' get('name' pop('price' {'name' 'shares' pop('price''not found''not foundm {'name''aa''shares' setdefault('price' {'name''aa''shares' 'price' setdefault('shares' (continues on next page builtin types for representing data
4,429
(continued from previous page{'name''aa''shares' 'price' setdefault('name''aab{'rise' 'fall': update(bm {'rise' 'name''aa''fall' 'shares' 'price' notem items() keys(and values(returns the result as iteratorwhich can be changed into list using 'list()methodm {'name''aa''shares': 'value': {'name''aa''shares' 'value' items( dict_items([('name''aa')('shares' )('value' )] list(ii [('name''aa')('shares' )('value' ) list( values() ['aa' set types set is an unordered collection of unique items unlike sequencesset does not provide indexing unlike dictionaryset does not provide key associated with values the items placed in the set must be immutable list can not be saved in set as shown belows set(type(ss add([ ]mutable objects list can not be saved in set traceback (most recent call last)file ""line in typeerrorunhashable type'lists add(( ) {( )immutable objects tuple can be saved in set add( { ( )sets are of two types 'setand 'frozensetabove codes are the example of setwhich is mutable in naturewhereas 'frozensetis immutable add operation can not be performed on frozenset builtin types for representing data
4,430
table shows various operations that can be performed on both sets and frozensetsitem len(ss copy( difference(ts intersection(ts isdisjoint(ts isubset(ts issuperset(ts symmetric_difference(ts union(ttable methods and operations for set types description total number of items in makes copy of return items in but not in the 'tcan be any iterator listtuple or set returns common in both and returns 'trueif nothingis common in and returns 'trueif is subset of returns 'trueis is superset of returns all the items from and twhich are not common in and returns all items from and some of the operations of table are shown belowa [ set(achange 'ato set duplicate entries are removed { [ difference( { set(ts difference( { mutable sets provides some additional methods as shown in table operation on this table will update the set after execution of the commands table methods for mutable set type item description add(itemadd item to clear(remove all items from difference_update(tremvoes all items from swhich are in discard(itemremove item form no error if item not present intersection_update computes the intersetion of and pop(remove an element from remove(itemremove item from if not foundraise keyerror symmetric_difference_update(tsave uncommon entries in and to update(tadd all entries of iterator 'tto some of the operations of table are shown belows { [ add( { symmetric_difference_update(ts (continues on next page builtin types for representing data
4,431
(continued from previous page{ builtin types for representing program structure everything in python is the object including functionsclasses and modules therefore functionsclasses and modules can be manipulated as data table shows various types that are used to represent various element of program itselftype category callable modules classes types table builtin types for program structure type name description types builtinfunctiontype builtin function or method type type of builtin types and classes object ancestor of all types and classes types functiontype user defined funtions types methodtype class method types moduletype module object ancestor of all types and classes type type of builtin types and classes notein table 'objectand 'typeare appeared twices because 'classesand 'typesare callable as function callable types callable types represent objects which can be called as function builtin functionsuser-define functionsinstance method and classes etc user-defined functions user-defined functions are callable functions that are created at module level by using 'defstatement or with 'lambdaoperatoras shown belowdef add num(xy)return( +ydiff num lambda xyx- add num( diff num( various attributes of user-defined functions are shown in table builtin types for representing program structure
4,432
table attributes for user-defined function 'fattributes description __doc__ documentation string __name__ function name __dict__ dictionary containing function attributes __code__ byte-compiled code __defaults__ tuple containing default arguments __globals__ dictionary defining the global namespace __closure__ tuple containing data related to nested scope some of the operations of table are shown belowdef mathex(ab)""calculate ( + )* ""global ( bx return mathex( mathex __doc__ calculate ( + )* mathex __globals__ {'__loader__''__builtins__''__spec__'none'__package__'none'__name__''__main__'' ' 'mathex''__doc__'none methods methods are the functions that are defined inside the class there are three types of methods instance methodclass method and static method following is an example of all three methodsclass spam()num class variable def __init__(selfnum )self num num def imethod(self)print instance variable print("imethod "self num@classmethod def cmethod(cls)print class variable print("cmethod "cls num@staticmethod def smethod(num)print variable defined in the file print("smethod "nums spam( imethod((continues on next page builtin types for representing program structure
4,433
(continued from previous pageimethod cmethod(cmethod num - smethod(smethod - note thatcalling function two step process as shown below imethod type(ii is method (imethod make function call using ( iu spam imethod type(iuiu(simethod function (not methodinstance of the class must be passed in function type(itype(ctype(linstance-method is 'method classmethod is 'methodstaticmethod is 'functionc cmethod (cmethod smethod (smethod - cu spam cmethod cu(cmethod lu spam smethod lu(smethod - notemethod ( imethodis callable object that wraps both function and the associated instance when we call the methodthe instance is passed to the method as the first parameter (self)but does not invoked teh function call operator then(can be used to invoke the function call as shown in above examplewhereasthe function (spam imethodwraps only method function (not the instance)therefore instance need to passed explicitly table shows the attributes available for the method-objects builtin types for representing program structure
4,434
table attributes for the methods attributes description __doc__ documentation string __name__ method name __class__ name of the class where method is defined __func__ function object implementing the method __self__ instance associated with the method (none if unbound classes and instances are callable class objects and instances operate as callable objects class object is created by the 'classstatement and is called as function in order to create new instance the arguments passed in the to the function are passed to __init__(methodwhich initialize the newly created instance an instance can emulate the function if it defines the special method __call__(if method is defined for an instance ' 'then methodname(argsactually invokes the method methodname __call__(argsclass foo(object)def __init__(selfval)self value val def addvalue(selfnum)print(self value numf foo( class is called as function to create new instance addvalue( addvalue __call__( addvalue __call__( classtypes and instances when we define classthen the class definition produces an object of type 'type'as shown below table shows the various attributes available for the classclass foo()pass type(footable class attributes attributes description __doc__ documentation string __name__ class name __bases__ tuple of base classes __dict__ dictionary holding the class methods and variables __module__ module name in which the class is defined __abstractmethods__ set of abstract method names the instance of the class has some special attributes shown in table builtin types for representing program structure
4,435
table instance attributes attributes description __class__ name of the class for instance __dict__ dictionary holding the instance data notethe __dict__ attribute is normally where all the data associated with an instance is stored however this behaviour can be changed by using __slots__ which is more efficient way for handling the large number of instances in that case__dict__ attribute will not be available for the instance modules module type is container that holds object loaded with 'importstatement whenever an attribute of the module is referencesthen corresponding dictionary is invoked invokes __dict__[' 'table shows the various attributes available for module table module attributes attributes description __dict__ dictionary associated with module __doc__ documenatation string __name__ name of module __file__ file from which module is loaded __path__ fully qualified package name special methods in this sectionvarious special method are listed which handle different situations object creation and destruction table shows three methods which are used to create and delete the objects table object creation and destruction method description __new__(cls [,*args [,**kwargs]]called to create new object __init__(self[,*args [,**kwargs]]called to initialize new instance __del__(selfcalled to delete an instance string representation table shows three methods which are used with string objectstable string representation method description __format__(selfformat_speccreates formatted string __repr__(selfcreates string representation of an object __str__(selfcreate simple string representation special methods
4,436
type checking table shows two methods which are used for type checkingtable type checking method result __instancecheck__(clsobjectisinstance(objectcls__subclasscheck__(clssubissubclass(subclsattribute access table shows the methods which are used to access the attribute using dot operator method __getattribute__(selfname__getattr__(selfname__setattr__(selfnamevalue__delattr__(selfnametable attribute access description returns attribute self name returns attribute self name if not found through normal attribute lookup or raise error sets value of the attribute delete the attribute notewhenever an attribute is accessedthen __getattribute__ is invoked if attribute is not foundthen __getattr__ is invoked thedefault behavior of __getattr__ is to raise 'attributeerrordescriptors subtle aspect of attribute manipulation is that sometimes the attributes of an object are wrapped with an extra layer of logic with getset and delete operations this can be achieved with descriptors with three options which are listed in table table shows the methods which are used to table special methods for descriptor objects method description __get__(selfinstanceclsreturn the attribute value or raise error __set__(selfinstancevalueset the attribute to value __delete__(selfinstancedelete the attribute sequence and mapping methods table shows the methods which are used to emulate the sequences and mapping objects table methods for sequences and mappings method description __len__(selfreturns length of self __getitem__(selfkeyreturns self[key__setitem__(selfkeyvalue sets self[key]=value __delitem__(selfkeydeletes self[key__contains__(selfobjreturns true if obj is in self special methods
4,437
iteration table shows the methods which are used with iterators furtherfollowing example is added for better understanding of the tablex [ __iter__( __next__( __next__( complete code for iteration [ __iter__(while tryprint( __next__()end=""except stopiterationbreak outputs table method for iterator method description obj __iter__(returns the iterator object iter __next__(return the next object or raise stopiteration error callable interface an instance can be used as function if the class method contains __call__ methodclass foodef __init__(selfnum)self num num def __call__(selfgreeting)print("{}the name of the class is '{}'format(greetingself __class__ __name__) foo( ('hello'instance is used as function hellothe name of the class is 'foo##############another example #########################class spamdef __init__(selfa= = )self self def __call__(selfa= = )self self (continues on next page special methods
4,438
(continued from previous pageinvoke __init__ spam(print("__init__ " as b__init__ invoke __call__ ( print("__call__ " as b__call__ context management protocol the 'withstatement allows statements to execute under the control over another object known as "context managerthe context manager has two methods __enter__ and __exit__ as shown in table methods __enter__(self__exit__(selftypevaluetbtable methods for context management description called when entering new context called when leaving the context if an exception occurred'type''valueand 'tbhave the exception typevalue and traceback information primary use of the context management interface is to allow for simplified resource control on objects involving system state filesnetworks connection and database etc by implementing this interfacean object can safely clean up resources when execution leaves context in which the object is being used object inspection and dir(the dir(function is used to inspect the objectswhich returns all the attributes of the objects to provide only useful information about the objectit can be overwritten using __dir__(selfas shown belowclass spamdef __init__(selfa= = )self self def __call__(selfa= = )self self def __dir__(self)return ['__init__''__call__''add more' spam(dir( ['__call__''__init__''add more' special methods
4,439
exception handling introduction exception handling is the process of handling the run time error error may occur due to missing data and invalid data etc these error can be catch in the runtime using try-except block and then can be processed according to our need this presents some of the examples of error handling for this first create new file with missing data in itas shown below here 'pricecolumn is empty for silver cat price_missing csv date,metal,radius,price,quantity "","gold", , , "","silver", ,, "","iron", , , "","gold", , , "","copper", , , "","iron", , , now try to calculate the total price for this file using 'ring_costfunction valueerror will be displayed as shown belowfrom price import ring_cost ring_cost('price_missing csv'traceback (most recent call last)row[ float(row[ ]price valueerrorcould not convert string to float try-except block the problem discussed in above section can be solved using try-except block in this blockthe 'trystatement can be used to try the string to float/int conversionand if it fails then 'exceptblock can be used to skip the processing of that particular rowas shown belowprice py import csv def ring_cost(filename)''calculate the total cost ''(continues on next page
4,440
(continued from previous pagetotal_price for all items in the list with open(filename' 'as fopen file in read mode rows csv reader(fheader next(rowsskip line header for row in rowstryrow[ float(row[ ]price row[ int(row[ ]quantity except valueerrorprocess valueerror only print("invalid datarow is skipped"continue total_price +row[ row[ print("total price % ftotal_pricereturn total_price return total_price def main()total ring_cost('price csv'function call print("total price % totalprint value standard boilerplate main is the starting function if __name__ ='__main__'main(now process the file again and the processing will skip the invalid line and display the total price from price import ring_cost ring_cost('price_missing csv'invalid datarow is skipped report error in previous sectionthe invalid data was ignored and message was printed but it is better give some details about the error as wellwhich is discussed in this section type of error in the below codethe type of the error is printed on the screen price py import csv def ring_cost(filename)''calculate the total cost ''total_price for all items in the list with open(filename' 'as fopen file in read mode rows csv reader(fheader next(rowsskip line header for row in rowstryrow[ float(row[ ]price (continues on next page report error
4,441
(continued from previous pagerow[ int(row[ ]quantity except valueerror as errprocess valueerror only print("invalid datarow is skipped"print('reason :'errcontinue total_price +row[ row[ print("total price % ftotal_pricereturn total_price return total_price def main()total ring_cost('price csv'function call print("total price % totalprint value standard boilerplate main is the starting function if __name__ ='__main__'main(notedo not forget to restart the python shell after changing the code from price import ring_cost ring_cost('price_missing csv'invalid datarow is skipped reason could not convert string to float location of error we can use the 'enumerateto display the location of the error price py import csv def ring_cost(filename)''calculate the total cost ''total_price for all items in the list with open(filename' 'as fopen file in read mode rows csv reader(fheader next(rowsskip line header for row_numrow in enumerate(rowsstart= )start from not tryrow[ float(row[ ]price row[ int(row[ ]quantity except valueerror as errprocess valueerror only print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)continue total_price +row[ row[ print("total price % ftotal_pricereturn total_price return total_price def main()(continues on next page report error
4,442
(continued from previous pagetotal ring_cost('price csv'function call print("total price % totalprint value standard boilerplate main is the starting function if __name__ ='__main__'main(now run the code again and it will display the location of the errorfrom price import ring_cost ring_cost('price_missing csv'invalid datarow is skipped row reason could not convert string to float catch all error (bad practicein previous sectionswe catch the specific error 'valueerrorwe can catch all types of errors as well using 'exceptionkeywordbut this may result in misleading messagesas shown in this section first replace the 'valueerrorwith 'exceptionas belowprice py import csv def ring_cost(filename)''calculate the total cost ''total_price for all items in the list with open(filename' 'as fopen file in read mode rows csv reader(fheader next(rowsskip line header for row_numrow in enumerate(rowsstart= )start from not tryrow[ float(row[ ]price row[ int(row[ ]quantity except exception as errprocess valueerror only print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)continue total_price +row[ row[ print("total price % ftotal_pricereturn total_price return total_price def main()total ring_cost('price csv'function call print("total price % totalprint value standard boilerplate main is the starting function if __name__ ='__main__'main(now run the code and it will work fine as shown below catch all error (bad practice
4,443
from price import ring_cost ring_cost('price_missing csv'invalid datarow is skipped row reason could not convert string to float nextreplace the 'intwith 'integerat line we are introducing error in the code price py import csv def ring_cost(filename)''calculate the total cost ''total_price for all items in the list with open(filename' 'as fopen file in read mode rows csv reader(fheader next(rowsskip line header for row_numrow in enumerate(rowsstart= )start from not tryrow[ float(row[ ]price row[ integer(row[ ]quantity except exception as errprocess valueerror only print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)continue total_price +row[ row[ print("total price % ftotal_pricereturn total_price return total_price def main()total ring_cost('price csv'function call print("total price % totalprint value standard boilerplate main is the starting function if __name__ ='__main__'main(now run the code again and it will give display following messageswhich has no relation with the actual error actual error is the 'integerat line since the conversion operation can not be performed now (due to invalid type 'integer')therefore error is catch for all the rows and the messages are generated for each row therefore it is very bad idea to catch errors using "exceptionkeyword from price import ring_cost ring_cost('price_missing csv'invalid datarow is skipped row reason name 'integeris not defined invalid datarow is skipped row reason could not convert string to floatinvalid datarow is skipped row reason name 'integeris not defined invalid datarow is skipped row reason name 'integeris not defined invalid datarow is skipped row reason name 'integeris not defined invalid datarow is skipped row reason name 'integeris not defined catch all error (bad practice
4,444
silencing error sometimes it is undesirable to display the error messages of the except blocks in such caseswe want to silent the error messageswhich is discussed in this section firstundo the changes made in previous sectioni replace 'integerwith 'intand 'exceptionwith 'valueerrornowwe will consider the following three cases to handle the error silent do not display error message warn display the error message stop stop execution of codeif error is detected for this one positional argument 'modeis definedwhose default value is set to 'warn'and then put the 'printstatement inside the 'if-elseblock it is good idea to set the default value of 'modeto 'warnas we do not want to pass the error silently listing silencing error price py import csv warn is kept as defaultas error should not be passed silently def ring_cost(filenamemode='warn')''calculate the total cost ''total_price for all items in the list with open(filename' 'as fopen file in read mode rows csv reader(fheader next(rowsskip line header for row_numrow in enumerate(rowsstart= )start from not tryrow[ float(row[ ]price row[ int(row[ ]quantity except valueerror as errprocess valueerror only if mode ='warn'print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)elif mode ='silent'pass do nothing elif mode ='stop'raise raise the exception continue total_price +row[ row[ print("total price % ftotal_pricereturn total_price return total_price def main()total ring_cost('price csv'function call print("total price % totalprint value standard boilerplate main is the starting function if __name__ ='__main__'main(below are the outputs for each of the cases code-block:python from price import ring_cost ring_cost('price_missing csv'default 'warn(continues on next page silencing error
4,445
(continued from previous pageinvalid datarow is skipped row reason could not convert string to float ring_cost('price_missing csv'mode='warn'invalid datarow is skipped row reason could not convert string to float ring_cost('price_missing csv'mode='silent' ring_cost('price_missing csv'mode='stop'traceback (most recent call last)file ""line in file "/media/dhriti/work/git/advance-python-tutorials/codes/price py"line in ring_cost row[ float(row[ ]price valueerrorcould not convert string to float list of exception in python following is the list of exceptions available in pythonbaseexception +-systemexit +-keyboardinterrupt +-generatorexit +-exception +-stopiteration +-stopasynciteration +-arithmeticerror +-floatingpointerror +-overflowerror +-zerodivisionerror +-assertionerror +-attributeerror +-buffererror +-eoferror +-importerror +-modulenotfounderror +-lookuperror +-indexerror +-keyerror +-memoryerror +-nameerror +-unboundlocalerror +-oserror +-blockingioerror +-childprocesserror +-connectionerror +-brokenpipeerror +-connectionabortederror +-connectionrefusederror +-connectionreseterror +-fileexistserror +-filenotfounderror +-interruptederror (continues on next page list of exception in python
4,446
(continued from previous page+-isadirectoryerror +-notadirectoryerror +-permissionerror +-processlookuperror +-timeouterror +-referenceerror +-runtimeerror +-notimplementederror +-recursionerror +-syntaxerror +-indentationerror +-taberror +-systemerror +-typeerror +-valueerror +-unicodeerror +-unicodedecodeerror +-unicodeencodeerror +-unicodetranslateerror +-warning +-deprecationwarning +-pendingdeprecationwarning +-runtimewarning +-syntaxwarning +-userwarning +-futurewarning +-importwarning +-unicodewarning +-byteswarning +-resourcewarning conclusion in this we saw various ways to handle the error along with some good practices in next we will discuss the 'data manipulationtechniques using various data structures available in python conclusion
4,447
data mining processing the data from large file and finding patterns in it is known as data-mining data mining required lots of data cleaning and data transformation operations in this sectionwe will see some of these operations building data structure from file in the previous we read the data from the file and then process the data in this sectionwe will save the data in list/dictionary and then use these data structure to process the data we will see that the data processing operations become easier when the data is converted in the form of dictionary importantin previous we read the file and calculated the total prices inside the function 'ring_costthe problem with this method is that the read data is no longer available (after the return statementfor the further processing thereforeit is good idea to save the results in list or dictionaryso that it will be available for other functions as wellas shown in this lets see the contents of the 'price csvfile againcat price csv date,metal,radius,price,quantity "","gold", , , "","silver", , , "","iron", , , "","gold", , , "","copper", , , "","iron", , , save and read data in list create new file 'datamine pywith following contents these contents are same as listing except it returns the list alsoa check is applied for input 'modevalue datamine py import csv def read_file(filenamemode='warn')''read csv file and save data in the list ''(continues on next page
4,448
(continued from previous pagecheck for correct mode if mode not in ['warn''silent''stop']raise valueerror("possible modes are 'warn''silent''stop'"ring_data [create empty list to save data with open (filename' 'as frows csv reader(fheader next(rowsskip the header change the types of the columns for row in rowstryrow[ float(row[ ]radius row[ float(row[ ]price row[ int(row[ ]quantity except valueerror as errprocess value error only if mode ='warn'print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)elif mode ='silent'pass do nothing elif mode ='stop'raise raise the exception continue append data in list in the form of tuple ring_data append(tuple(row)return ring_data def main()ring_data read_file('price csv'total rows in the file print("total rows"len(ring_data)total price calculation total_price for row in ring_datatotal_price +row[ row[ print("total price{: }format(total_price)if __name__ ='__main__'main(run the above code and we will get the following resultspython datamine py total rows total price nowopen the python shell and run the below code see the difference"previously we returned total_price from the functiontherefore we could perform no more operation on the data butnow we have the data in the form of listtherefore we can perform operation on the data from datamine import read_file ring_data read_file('price csv'len(ring_data ring_data[ (continues on next page building data structure from file
4,449
(continued from previous page('''gold' for data in ring_dataprint metal with radius if data[ print("metal{ }radius{ }format(data[ ]data[ ])metalsilverradius metalironradius `data_in_dict`save and read data in dictionary in the previous sectionthe list is read and data is printed ( name of metal when radius it worked fine therebut when we have large number of columns in the listthen it is very difficult to locate the elements using positions 'data[ ]for easy referencinga dictionary can be used as shown below note thatat line the elements are located by the namei row['price']which is easier to handle than using index row[ datamine py import csv def read_file(filenamemode='warn')''read csv file and save data in the list ''check for correct mode if mode not in ['warn''silent''stop']raise valueerror("possible modes are 'warn''silent''stop'"ring_data [create empty list to save data with open (filename' 'as frows csv reader(fheader next(rowsskip the header change the types of the columns for row in rowstryrow[ float(row[ ]radius row[ float(row[ ]price row[ int(row[ ]quantity except valueerror as errprocess value error only if mode ='warn'print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)elif mode ='silent'pass do nothing elif mode ='stop'raise raise the exception continue ring_data append(tuple(row)append data in list in the form of tuple row_dict 'daterow[ ](continues on next page building data structure from file
4,450
(continued from previous page'metalrow[ ]'radiusrow[ ]'pricerow[ ]'quantityrow[ ring_data append(row_dictreturn ring_data def main()ring_data read_file('price csv'total rows in the file print("total rows"len(ring_data)total price calculation total_price for row in ring_datatotal_price +row['price'row['quantity'print("total price{: }format(total_price)if __name__ ='__main__'main(following is the output of above codepython datamine py total rows total price list comprehension in previous sectionwe read the data from the file and stored in the list/dictionary to perform further operations in this sectionwe will extract specific type of data and store them in new list let' do it in the python shell as belowbasic method for extraction in the below codeif-statement along with the 'loopis used to extract the desired datai radius from datamine import read_file ring_data read_file('price csv'small_ring [for ring in ring_dataif ring['radius' store radius small_ring append((ring['metal']ring['radius']for ring in small_ringdisplay content of small_ring print(ring('copper' ('iron' list comprehension ring['price'])
4,451
list comprehension for extraction operation in above sectioni if statement with loopis very commontherefore python provide way to do it in one linewhich is known as 'list comprehension'as shown belowfrom datamine import read_file ring_data read_file('price csv'small_ring [small_ring [(ring['metal']ring['radius']ring['price']for ring in ring_data if ring['radius' for ring in small_ringprint(ring('copper' ('iron' lambda operator in numref:data_in_dictthe data was saved in the dictionary and then specific type of data is extraced in above setion in this sectionwe will sort the data store in the dictionary basis method for sorting let' do it in the python shell as shown below first see the content of the dictionary againfrom datamine import read_file ring_data read_file('price csv'for data in ring_dataprint(data{'date''''metal''gold''radius' 'price' 'quantity' {'date''''metal''silver''radius' 'price' 'quantity' {'date''''metal''iron''radius' 'price' 'quantity' {'date''''metal''gold''radius' 'price' 'quantity' {'date''''metal''copper''radius' 'price' 'quantity' {'date''''metal''iron''radius' 'price' 'quantity' note thatunlike listwe can not perform the sort(operation on dictionary we will have following errorring_data sort(traceback (most recent call last)file ""line in typeerror'<not supported between instances of 'dictand 'dictto sort the data in dictionarywe need to provide 'keyto the sort(method the key can be extracted from the dictionary using function then this function should be called using sort(method as shown below list comprehension
4,452
notesort(method has the 'keyargument it is not user-defined name def sort_name(all_data)return all_data['metal'ring_data sort(key=sort_namesort the data for data in ring_dataprint(data{'date''''metal''copper''radius' 'price' 'quantity' {'date''''metal''gold''radius' 'price' 'quantity' {'date''''metal''gold''radius' 'price' 'quantity' {'date''''metal''iron''radius' 'price' 'quantity' {'date''''metal''iron''radius' 'price' 'quantity' {'date''''metal''silver''radius' 'price' 'quantity' lambda operator the problem with above method is that we need to define one line function for each key 'metal''priceand 'radiusetc (if we want to sort on every key)which is not desirable coding-style lambda operators are the one operators which can be used to replace the one line function let' see some example of lambda operator firstsq lambda ** sq( one line function for ** sum num lambda xy lambda operator with two variable sum num( notein 'sq lambda ** 'the 'xis the input argument to function and the value after ':' ** is the return value and 'sqis the name of the function the statement is equivalent to below codedef sq( )return ** nowwe will use the sort(method using lambda operator as shown belowring_data sort(key=lambda all_data all_data['metal']for data in ring_dataprint(data(continues on next page list comprehension
4,453
(continued from previous page{'date''''metal''copper''radius' 'price' 'quantity' {'date''''metal''gold''radius' 'price' 'quantity' {'date''''metal''gold''radius' 'price' 'quantity' {'date''''metal''iron''radius' 'price' 'quantity' {'date''''metal''iron''radius' 'price' 'quantity' {'date''''metal''silver''radius' 'price' 'quantity' find and arrange gold rings let' add list comprehension and lambda operator in the file 'datamine pyin the below codethe gold rings are extracted firstand then the rings are arranged in decreasing order according to radius listing find and arrange gold rings datamine py import csv def read_file(filenamemode='warn')''read csv file and save data in the list ''check for correct mode if mode not in ['warn''silent''stop']raise valueerror("possible modes are 'warn''silent''stop'"ring_data [create empty list to save data with open (filename' 'as frows csv reader(fheader next(rowsskip the header change the types of the columns for row in rowstryrow[ float(row[ ]radius row[ float(row[ ]price row[ int(row[ ]quantity except valueerror as errprocess value error only if mode ='warn'print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)elif mode ='silent'pass do nothing elif mode ='stop'raise raise the exception continue (continues on next page find and arrange gold rings
4,454
(continued from previous pagering_data append(tuple(row)append data in list in the form of tuple row_dict 'daterow[ ]'metalrow[ ]'radiusrow[ ]'pricerow[ ]'quantityrow[ ring_data append(row_dictreturn ring_data def main()ring_data read_file('price csv'total rows in the file print("total rows"len(ring_data)total price calculation total_price for row in ring_datatotal_price +row['price'row['quantity'print("total price{: }format(total_price)extract gold-ring using list comprehension gold_ring [ring for ring in ring_data if ring['metal'='gold'for ring in gold_ringprint metal and radius print("metal{ }radius{ }format(ring['metal']ring['radius'])reverse-sort the data in gold_ring using lambda operators gold_ring sort(key=lambda data data['radius']reverse=trueprint("\nradius in descending order:"for ring in gold_ringprint metal and radius print("metal{ }radius{ }format(ring['metal']ring['radius'])if __name__ ='__main__'main(now execute the file and we will get the following resultspython datamine py metalgoldradius metalgoldradius radius in descending ordermetalgoldradius metalgoldradius conclusion in this we store the data in the list and dictionary then we perform the extraction operation on the dictionary using 'list comprehensionlastly we used the 'lambda operatorfor sorting the data in the dictionary conclusion
4,455
object oriented programming pythonic style in this we will see the basic differences between the oops methods in python and other programming languages +and java etc this understanding is essential to use the python language effectivelyand to write the code in pythonic waysi not converting ++/java code into python code here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology simple data structure to classes in this sectionwe will convert our previous codes into classes instance variable first create classwhich can contain various columns of the csv file as shown in the below code please note the following points__init__ is the initializer (often called the constructor)which initializes the instance variables self radiusself date and self metal are the instance variables which are created by the __init__ pythonic py import math class ring(object)""here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology ""def __init__(selfdatemetalradiuspricequantity)""init is not the constructorbut the initializer which initialize the instance variable self is the instance __init__ takes the instance 'selfand populates it with the radiusmetaldate etc and store in dictionary (continues on next page
4,456
(continued from previous pageself radiusself metal etc are the instance variable which must be unique ""self date date self metal metal self radius radius self price price self quantity quantity def cost(self)return self price self quantity def area(self)return math pi self radius** object of class let' create an object 'rof the class 'ring'to verify the operation of the classas shown belowfrom pythonic import ring ring(" = - ""gold" metal 'goldr cost( area( class variable and initialization letsadd some class variables to the above class and define some initial values to the arguments in the __init__ function as shown belownoteclass variable should be used to create the shared variables it is always good to put the shared variables on the class level rather than instance level pythonic py import math import time class ring(object)""here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology ""class variables date time strftime("% -% -% "time gmtime()today' date "yyyy-mm-ddcenter center of the ring def __init__(selfdate=datemetal="copper"radius= price= quantity= )(continues on next page simple data structure to classes
4,457
(continued from previous page""init is not the constructorbut the initializer which initialize the instance variable self is the instance __init__ takes the instance 'selfand populates it with the radiusmetaldate etc and store in dictionary self radiusself metal etc are the instance variable which must be unique ""self date date self metal metal self radius radius self price price self quantity quantity def cost(self)return self price self quantity def area(self)return math pi self radius** lets check the functionality of the above codepython - pythonic py note that we used '-ioptiontherefore there is no need to import the class 'ringas shown in below coder ring(no paratmer pass therefore default values will be used date instance variable ' radius instance variable center class variable cost(class method area(class method alsowe can modify the instance and class variables values as shown belowr price current value quantity cost( quantity= modify instance variable cost(price is changed to center modify class variable center notethe value of the variables are stored in the dictionarywhose contents can be seen using '__dict__' simple data structure to classes
4,458
__dict__ {'date''''metal''copper''radius' 'price' 'quantity' 'center' shipping product and agile methodology in previous sectionwe create the object of the class in the python shell nowwe will create object of the class in the file itselfas show belowimportantnote thatat this momentwe did not add to many features to class in listing we added only two methods here 'areaand 'costnowwe are ready to ship this product to our customers we will add more features according to feedback provided by the costumers as shown in subsequent sections this is called the 'agilemethodology this will give us chance to understand the psychology behind the several elements of the python language listing shipping product is ready pythonic py import math import time class ring(object)""here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology ""class variables date time strftime("% -% -% "time gmtime()today' date "yyyy-mm-ddcenter center of the ring def __init__(selfdate=datemetal="copper"radius= price= quantity= )""init is not the constructorbut the initializer which initialize the instance variable self is the instance __init__ takes the instance 'selfand populates it with the radiusmetaldate etc and store in dictionary self radiusself metal etc are the instance variable which must be unique ""self date date self metal metal self radius radius self price price self quantity quantity def cost(self)return self price self quantity (continues on next page shipping product and agile methodology
4,459
(continued from previous pagedef area(self)return math pi self radius** def main()print("center of the ring is at:"ring centermodify class variable ring(price= modify only price print("radius:{ }cost:{ }format( radiusr cost())if __name__ ='__main__'main(following are the results for above codepython pythonic py center of the ring is at radius: cost: attribute access before moving furtherlet us understand the attribute access ( variable in the classgetset and del in pythoneverything is an object and there are only three operations which can be applied to the objects get set delete these operations are used as belowfrom pythonic import ring ring( metal get operation 'copperr metal "goldset operation metal 'golddel metalr dater price delete operation metal traceback (most recent call last)file ""line in attributeerror'ringobject has no attribute 'metalr __dict__ only radius and quantity left {'radius' 'quantity' warningif attribute does not exist in the dictionarythen it will be createde in the below codewe used metals (plural metalsfor the metal name instead of metaltherefore new attribute will be created hencebe careful while setting the attributes of the class metals "ironadd item to dict __dict__ {'radius' 'quantity' 'metals''iron' attribute access
4,460
notethe class method has two layers of the get-set-del operations as shown belowr area( ( area)((layer )(layer area layer (layer getattrsetattr and delattr getattrsetattr and delattr are invoked when we use the getset and delete operations respectively the knowledge of these methods can be very useful in writing the general purpose codes as shown in section below an example of getattr and setattrwhere the columns are printed using 'getattrnote that the code is generalized hereas we can print all the columns using one statement only lines - from pythonic import ring ring(getattr( 'metal'get 'coppersetattr( 'metal''gold'set metal 'goldout_col ['metal''radius''quantity'for col in out_colprint columns and value using getattr print("{ { }format(colgetattr(rcol))metal gold radius quantity delattr( 'metal'delete 'metalr __dict__ 'metalis removed from dictionary {'date''''radius' 'price' 'quantity' users lets assume that we have two types of users for our product one of them is 'mathematicianwho is using our product for the mathematical analysis of the datawhereas the other is 'contributer'who is implementing additional features to the product both of them will provide some feedbacks according to their need and we will modify our class to meet their requirement average area the first useri mathematicianuses our design to calculate the average area of the ringas shown below users
4,461
listing average area mathematician py user- using ring py for mathematical analysis from random import randomseed from pythonic import ring def calc_avg_area( = seed_value= )seed for random number generator seed(seed_valuerandom radius rings [ring(radius=random()for in range( )total for in ringstotal + area(print values for each iteration print("% % % ( radiusr area()total)avg_area sum([ area(for in rings])/ return avg_area def main()generate 'nrings avg_area calc_avg_area( = print("\naverage area for ={ is /{ { }format(navg_area)if __name__ ='__main__'main(following is the result of above codepython mathematician py average area for = is / table formatting the second useri contributorhas added the table-formatting functionality for class 'ringnotethe code is generalized format as compared to listing following are the changes made hereat line the conversion is generalized using 'list comprehensionthe function 'print_table (lines - )is generalized using 'getattrmethod herewe can print desired columns of the table by passing list of 'column names users
4,462
listing table formatter contributor py user- additional features will be added to pythonic py by the contributor import csv from pythonic import ring this code is copied from datamine py file and modified slightly to include the type of the data def read_file(filenametypesmode='warn')''read csv file and save data in the list '' check for correct mode if mode not in ['warn''silent''stop']raise valueerror("possible modes are 'warn''silent''stop'" ring_data [create empty list to save data with open (filename' 'as frows csv reader(fheader next(rowsskip the header change the types of the columns for row in rowstryrow[ float(row[ ]radius row[ float(row[ ]price row[ int(row[ ]quantity generalized conversion row [d_type(valfor d_typeval in zip(typesrow)except valueerror as errprocess value error only if mode ='warn'print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)elif mode ='silent'pass do nothing elif mode ='stop'raise raise the exception continue ring_data append(tuple(row) append data in list in the form of tuple row_dict 'daterow[ ]'metalrow[ ]'radiusrow[ ]'pricerow[ ]'quantityrow[ row_dict ring(row[ ]row[ ]row[ ]row[ ]row[ ]use below or above line row_dict ringdate row[ ]metal row[ ]radius row[ ]price row[ ](continues on next page users
4,463
(continued from previous page quantity row[ ring_data append(row_dict return ring_data table formatter def print_table(list_namecol_name=['metal''radius'])""print the formatted output "" for in col_nameprint header print("{:> }format( )end='print(print empty line for in list_nameprint values for in col_nameprint("{:> }format(str(getattr(lc)))end='print( def main()list correct types of columns in csv file types =[strstrfloatfloatint read file and save data in list list_data read_file('price csv'types formatted output print_table(list_dataprint(print_table(list_data['metal''radius''price'] if __name__ ='__main__'main(following are the output for the above codepython contributor py metal radius gold silver iron gold copper iron metal gold silver iron gold copper iron radius price requirement perimeter method in listing the mathematician calculated the average area supposemathematician want to do some analysis on the perimeter of the ring as welltherefore he asked us to add method to calculate the perimeter as well this is quite easy taskand can be implemented as below requirement perimeter method
4,464
pythonic py import math import time class ring(object)""here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology ""class variables date time strftime("% -% -% "time gmtime()today' date "yyyy-mm-ddcenter center of the ring def __init__(selfdate=datemetal="copper"radius= price= quantity= )""init is not the constructorbut the initializer which initialize the instance variable self is the instance __init__ takes the instance 'selfand populates it with the radiusmetaldate etc and store in dictionary self radiusself metal etc are the instance variable which must be unique ""self date date self metal metal self radius radius self price price self quantity quantity def cost(self)return self price self quantity def area(self)return math pi self radius** def perimeter(self)return math pi self radius def main()print("center of the ring is at:"ring centermodify class variable ring(price= modify only price print("radius:{ }cost:{ }format( radiusr cost())print("radius:{ }perimeter:{ : }format( radiusr perimeter())if __name__ ='__main__'main( no data hiding in python in previous sectionwe added the method 'perimeterin the design note thatin python all the attributes can be directly accessed by the clientsand there is no concept of data hiding in the python let' understand this by an example no data hiding in python
4,465
importantin the below codethe mathematician uses the attribute 'radiusdirectly by changing it to ' radius expansion( radius)at line then the new radius is used to calculate the perimeter at line in the other wordvalue of radius is changed in the dictionary itselfand then the method perimeter(is used for calculation such access to attributes is available in python onlywhereas other languages java and +etc uses the concept of data hiding (using private and protected variableand the attributes can not be directly accessed these languages provide some get and set method to access and modify the attributesi we can make local copy of the variable for further calculationwhereas in pythonthe value is changed in the dictionary itself data hiding is required in +and java etc as direct access can be serious problem there and can not be resolved in pythondata is not hidden from user and we have various methods to handle all kind of situations as shown in this listing accessing the class attribute directly mathematician py user- using ring py for mathematical analysis from random import randomseed from pythonic import ring def calc_avg_area( = seed_value= )seed for random number generator seed(seed_value random radius rings [ring(radius=random()for in range( ) total for in ringstotal + area(print values for each iteration print("% % % ( radiusr area()total)avg_area sum([ area(for in rings])/ return avg_area def expansion(radius= expansion= )radius *expansion times radius expansion due to heat return radius def main()generate 'nrings avg_area calc_avg_area( = print("\naverage area for ={ is /{ { }format(navg_area) radii [ list of radius rings [ring(radius=rfor in radiicreate object of different radius for in ringsprint("radius:" radiusprint("perimeter at room temperature% perimeter()radius after expansion radius expansion( radiusmodifying the attribute of the class print("perimeter after heating:% perimeter() if __name__ ='__main__'main(following is the output of above code no data hiding in python
4,466
python mathematician py radius perimeter at room temperature perimeter after heating: radius perimeter at room temperature perimeter after heating: radius perimeter at room temperature perimeter after heating: inheritance overview lets review the inheritance in python quickly then we will see some good usage of inheritance in this noteno prior knowledge of the 'super()and 'multiple inheritanceis required in this we will see various examples to understand these topics first create parent class "animalas belowclass animal(object)def __init__(selfname)self name name def sound(self)print("loud or soft sound"def wild(self)print("wild or pet animail" animal("tiger" sound(loud or soft sound nowcreate child class "petanimalwhich inherit the class "animal"class petanimal(animal)def pet_size(self)print("small or big" petanimal("cat" pet_size(small or big sound(inherit from animal loud or soft sound nextoveride the method of class "animalin the child class "dog"class dog(animal)def sound(self)print("dog barks" dog("tommy" sound(override the 'soundof class animal dog barks inheritance overview
4,467
we can use both parent and child class method with same name this can be done using 'super()as belowclass tiger(animal)def sound(self)print("tiger roars"super(sound(call the parent class 'soundt tiger("tigger" sound(invoke 'soundof both child and parent tiger roars loud or soft sound multiple inheritance is possible in pythonwhich can be used to handle complex situations below is an example of multiple inheritanceclass cat(tigeranimal)pass cat("kitty" sound(tiger roars loud or soft sound wild(wild or pet animail note thatpython creates mro (method resolution orderfor multiple inheritanceand if it can not be created then error will be reported the mro for class 'catis shown belowhelp(catclass cat(tigeranimalmethod resolution ordercat tiger animal if we inherit animal first and next tigerthen below error will occurbecause python uses 'child firstapproach and this inheritance will call the parent first mro will be "cat->animal->tigerand it will report error as it has 'parent firsti animal comes before tiger class rat(animaltiger)pass traceback (most recent call last)file ""line in typeerrorcannot create consistent method resolution order (mrofor bases animaltiger new user making boxes supposewe get another user for our class ring ( file pythonic py)who is creating boxes for the ring for he needs slightly greater perimeter of the box than the ring note that this user is inheriting the class 'ring'and overriding the method 'perimeter()at line as shown belowlisting box company modifying the class method 'perimeter() box py user- creating boxes for the ring (continues on next page new user making boxes
4,468
(continued from previous page from pythonic import ring class box(ring)""modified perimeter for creating the box "" def perimeter(self)override the method 'perimeterperimeter is increased times return ring perimeter(self def main() box(radius= pass radius print("radius:" radiusprint("modified perimeter% perimeter()( *pi*radius if __name__ ='__main__'main(following is the output of above codepython box py radius modified perimeter notenowwe have two users who are modifying the class attributes first is the mathematician (mathematician py)who is modifying the 'radiusin listing and other is the box companywho is modifying the method 'perimeterin listing lastlywe have contributor who is creating 'table formatterin listing for displaying the output nicely rewrite table formatter using inheritance abstract class the contributor decided to add more print-formats for the table for thishe decided to use inheritance to rewrite the code listing using inheritance alsothe contributor used the abstract class at line with two abstract methods the abstract methods are compulsory to be implemented in the child class importantthe abstract methods are compulsory to be implemented in the child class in the other wordsthe abstract class is the way to force the child class to implement certain methodwhich are decorated with 'abstractmethodhere the aim is to rewrite the code in listing such that we need not to change anything in the function 'main()in the other wordsif the main(function works fine as it isthen it ensures that the code will not break for the userswho are using listing for printing the table below is the modified listing listing print-format using inheritance contributor py user- additional features will be added to pythonic py by the contributor (continues on next page rewrite table formatter using inheritance
4,469
(continued from previous page from abc import abcabstractmethod import csv from pythonic import ring abstract class for table-format class tableformat(object)""abastract class "" @abstractmethod def heading(selfheader)must be implemented in child class pass @abstractmethod def row(selfrow_data)must be implemented in child class pass text format for table class textformat(tableformat)""text format for table "" def heading(selfheader)print headers for in headerprint("{:> }format( )end='print( def row(selfrow_data)print rows for in row_dataprint("{:> }format( )end='print( this code is copied from datamine py file and modified slightly to include the type of the data def read_file(filenametypesmode='warn')''read csv file and save data in the list '' check for correct mode if mode not in ['warn''silent''stop']raise valueerror("possible modes are 'warn''silent''stop'" ring_data [create empty list to save data with open (filename' 'as frows csv reader(fheader next(rowsskip the header change the types of the columns for row in rowstryrow[ float(row[ ]radius row[ float(row[ ]price row[ int(row[ ]quantity generalized conversion row [d_type(valfor d_typeval in zip(typesrow)except valueerror as errprocess value error only if mode ='warn'(continues on next page rewrite table formatter using inheritance
4,470
(continued from previous page print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)elif mode ='silent'pass do nothing elif mode ='stop'raise raise the exception continue ring_data append(tuple(row) append data in list in the form of tuple row_dict 'daterow[ ]'metalrow[ ]'radiusrow[ ]'pricerow[ ]'quantityrow[ row_dict ring(row[ ]row[ ]row[ ]row[ ]row[ ]use below or above line row_dict ringdate row[ ]metal row[ ]radius row[ ]price row[ ]quantity row[ ring_data append(row_dict return ring_data table formatter def print_table(list_namecol_name=['metal''radius']out_format=textformat())note that class is passed here ""print the formatted output "" for in col_nameprint header print("{:> }format( )end='print(print empty line for in list_nameprint values for in col_nameprint("{:> }format(str(getattr(lc)))end='print( invoke class-method for printing heading out_format heading(col_nameclass is passed to out_format for in list_namestore row in list row_data [str(getattr(lc)for in col_nameout_format row(row_datapass rows to class-method row( def main()list correct types of columns in csv file types =[strstrfloatfloatint read file and save data in list list_data read_file('price csv'types(continues on next page rewrite table formatter using inheritance
4,471
(continued from previous page formatted output print_table(list_dataprint(print_table(list_data['metal''radius''price'] if __name__ ='__main__'main(now run the code to see whether it is working as previously or not the below output is same as for listing python contributor py metal gold silver iron gold copper iron radius metal gold silver iron gold copper iron radius price csv format since the above code is working finetherefore the contributor can add as many format as possiblejust by adding new class in the below codehe added 'csv formatfor the printinglisting csv format is added contributor py user- additional features will be added to pythonic py by the contributor from abc import abcabstractmethod import csv from pythonic import ring abstract class for table-format class tableformat(object)""abastract class "" @abstractmethod def heading(selfheader)must be implemented in child class pass @abstractmethod def row(selfrow_data)must be implemented in child class pass text format for table (continues on next page rewrite table formatter using inheritance
4,472
(continued from previous page class textformat(tableformat)""text format for table "" def heading(selfheader)print headers for in headerprint("{:> }format( )end='print( def row(selfrow_data)print rows for in row_dataprint("{:> }format( )end='print( csv format for table class csvformat(tableformat)""text format for table "" def heading(selfheader)print headers print(',join(header) def row(selfrow_data)print rows print(",join(row_data) this code is copied from datamine py file and modified slightly to include the type of the data def read_file(filenametypesmode='warn')''read csv file and save data in the list '' check for correct mode if mode not in ['warn''silent''stop']raise valueerror("possible modes are 'warn''silent''stop'" ring_data [create empty list to save data with open (filename' 'as frows csv reader(fheader next(rowsskip the header change the types of the columns for row in rowstryrow[ float(row[ ]radius row[ float(row[ ]price row[ int(row[ ]quantity generalized conversion row [d_type(valfor d_typeval in zip(typesrow)except valueerror as errprocess value error only if mode ='warn'print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)elif mode ='silent'pass do nothing elif mode ='stop'raise raise the exception continue ring_data append(tuple(row) append data in list in the form of tuple (continues on next page rewrite table formatter using inheritance
4,473
(continued from previous page row_dict 'daterow[ ]'metalrow[ ]'radiusrow[ ]'pricerow[ ]'quantityrow[ row_dict ring(row[ ]row[ ]row[ ]row[ ]row[ ]use below or above line row_dict ringdate row[ ]metal row[ ]radius row[ ]price row[ ]quantity row[ ring_data append(row_dict return ring_data table formatter def print_table(list_namecol_name=['metal''radius']out_format=textformat())note that class is passed here ""print the formatted output "" for in col_nameprint header print("{:> }format( )end='print(print empty line for in list_nameprint values for in col_nameprint("{:> }format(str(getattr(lc)))end='print( invoke class-method for printing heading out_format heading(col_nameclass is passed to out_format for in list_namestore row in list row_data [str(getattr(lc)for in col_nameout_format row(row_datapass rows to class-method row( def main()list correct types of columns in csv file types =[strstrfloatfloatint read file and save data in list list_data read_file('price csv'types formatted output print_table(list_dataprint(print_table(list_data['metal''radius''price']out_format=textformat() print(print_table(list_data['metal''radius''price']out_format=csvformat() if __name__ ='__main__'(continues on next page rewrite table formatter using inheritance
4,474
(continued from previous page main(following is the output of above listingpython contributor py metal radius price gold silver iron gold copper iron metal,radius,price gold, , silver, , iron, , gold, , copper, , iron, , advance inheritance in this section__init__ function of parent class is inherited by the child class alsoa good usage of 'multiple inheritanceand 'class with one methodis shown printing outputs to files in listing the output can be printed on the screen only there we requested the contributorthat it will be better if we can save the output in the files as well to add this featurethe contributor decided to add an __init__ function to add the print functionality it is good approach otherwise we need to add the 'output-filelogic in each format-class below is the code for saving the data in file following are the functionality added to this designoutputs can be saved in the files csvformat gets this ability through inheriting the parent class __init__ textformat override the parent class __init__ to increase/decrease the width alsoit uses 'super()to inherit the parent class __init__ so that the output can be saved in the file listing print data in file and screen contributor py user- additional features will be added to pythonic py by the contributor import sys import csv from abc import abcabstractmethod from pythonic import ring abstract class for table-format class tableformat(object)""abastract class "" print data to file or screen (continues on next page advance inheritance
4,475
(continued from previous page def __init__(selfout_file=none)if out_file =nonestdout is the location where python prints the output out_file sys stdout self out_file out_file @abstractmethod def heading(selfheader)must be implemented in child class pass @abstractmethod def row(selfrow_data)must be implemented in child class pass text format for table class textformat(tableformat)""text format for table "" option for modifying width def __init__(selfwidth= out_file=none)override init inherit parent init as well to save data in file super(__init__(out_fileself width width def heading(selfheader)print headers for in headerprint("{ :>{ } }format(hself width)end='file=self out_fileprint(file=self out_file def row(selfrow_data)print rows for in row_dataprint("{ :>{ } }format(rself width)end='file=self out_fileprint(file=self out_file csv format for table class csvformat(tableformat)""text format for table "" init will be inherited from parent to save data in file def heading(selfheader)print headers print(',join(header)file=self out_file def row(selfrow_data)print rows print(",join(row_data)file=self out_file this code is copied from datamine py file and modified slightly to include the type of the data def read_file(filenametypesmode='warn')''read csv file and save data in the list '' check for correct mode if mode not in ['warn''silent''stop']raise valueerror("possible modes are 'warn''silent''stop'" ring_data [create empty list to save data (continues on next page advance inheritance
4,476
(continued from previous page with open (filename' 'as frows csv reader(fheader next(rowsskip the header change the types of the columns for row in rowstryrow[ float(row[ ]radius row[ float(row[ ]price row[ int(row[ ]quantity generalized conversion row [d_type(valfor d_typeval in zip(typesrow)except valueerror as errprocess value error only if mode ='warn'print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)elif mode ='silent'pass do nothing elif mode ='stop'raise raise the exception continue ring_data append(tuple(row) append data in list in the form of tuple row_dict 'daterow[ ]'metalrow[ ]'radiusrow[ ]'pricerow[ ]'quantityrow[ row_dict ring(row[ ]row[ ]row[ ]row[ ]row[ ]use below or above line row_dict ringdate row[ ]metal row[ ]radius row[ ]price row[ ]quantity row[ ring_data append(row_dict return ring_data table formatter def print_table(list_namecol_name=['metal''radius']out_format=textformat(out_file=none))note that class is passed here ""print the formatted output "" for in col_nameprint header print("{:> }format( )end='print(print empty line for in list_nameprint values for in col_nameprint("{:> }format(str(getattr(lc)))end='print((continues on next page advance inheritance
4,477
(continued from previous page invoke class-method for printing heading out_format heading(col_nameclass is passed to out_format for in list_namestore row in list row_data [str(getattr(lc)for in col_nameout_format row(row_datapass rows to class-method row( def main()list correct types of columns in csv file types =[strstrfloatfloatint read file and save data in list list_data read_file('price csv'types formatted output print_table(list_dataprint(print_table(list_data['metal''radius''price']out_format=textformat() print in file out_file open("text_format txt"" "open file in write mode print_table(list_data['metal''radius''price']out_format=textformat(out_file=out_file)out_file close( print in file with width out_file open("wide_text_format txt"" "open file in write mode print_table(list_data['metal''radius''price']out_format=textformat(width= out_file=out_file)out_file close( print(print_table(list_data['metal''radius''price']out_format=csvformat()print in file out_file open("csv_format csv"" "open file in write mode print_table(list_data['metal''radius''price']out_format=csvformat(out_file=out_file)out_file close( if __name__ ='__main__'main(following are the outputs of the above listing notethe previous main function is also working fine this check is very important to confirm that the codes of the exitsting user will not bread due to updating of the design python contributor py metal gold silver iron gold radius price (continues on next page advance inheritance
4,478
(continued from previous pagecopper iron metal,radius,price gold, , silver, , iron, , gold, , copper, , iron, , below are the contents of the file generated by above listingcat text_format txt metal gold silver iron gold copper iron radius price cat wide_text_format txt metal gold silver iron gold copper iron radius price cat csv_format csv metal,radius,price gold, , silver, , iron, , gold, , copper, , iron, , mixin multiple inheritance put quotes around data supposewe want to put quotes around all the data in printed output this can be accomplished as belowfrom contributor import class quotedata(textformat)def row(selfrow_data)put quotes around data quoted_data ['"{ }"format(rfor in row_datasuper(row(quoted_datatypes =[strstrfloatfloatintlist_data read_file('price csv'typesprint_table(list_data['metal''radius''price']out_format=quotedata()(continues on next page advance inheritance
4,479
(continued from previous pagemetal radius price "gold" " "silver" " "iron" " "gold" " "copper" " "iron" " notethe problem with above method is that it is applicable to class 'textformatonly (not to csvformatthis can be generalized using mixin as shown belowput quotes using mixin we can use mix two class as shown belowimportantplease note following points in the below codein pythoninheritance follows two rule child is checked before parent parents are checked in order the 'super()is used in he class "quotedata"which will call the __init__ function but this class does not inherit from any other class (or inherits from python-object classthe __init__ function function for the class "quotedatawill be decided by the child classi the class mixinquotecsv is inheriting "quotedataand "csvformatsincethe parents are checked in ordertherefore "quotedatawill be check first also"child is checked before parenti child will decide the super(function for the parent for examplesuper(function of "quotedatawill call the __init__ function of "parent of child class (not it' own parent)"hence __init__ of csvformat will be invoked by the "super()of quotedata the correct order of inheritance can be checked using 'helpas below if we have super(in all classes then super(of mixinquotetext will call the "quotedata"then super(of quotedata will call the textformat and so on from contributor import help(mixinquotetextclass mixinquotetext(quotedatatextformattext format for table method resolution ordermixinquotetext quotedata textformat tableformat builtins object warningit is not good idea to define class with one method but this feature can be quite powerful in the case of inheritanceas shown in below example listing adding quotes around printed data using mixin contributor py user- additional features will be added to pythonic py by the contributor (continues on next page advance inheritance
4,480
(continued from previous page import sys import csv from abc import abcabstractmethod from pythonic import ring abstract class for table-format class tableformat(object)""abastract class "" print data to file or screen def __init__(selfout_file=none)if out_file =nonestdout is the location where python prints the output out_file sys stdout self out_file out_file @abstractmethod def heading(selfheader)must be implemented in child class pass @abstractmethod def row(selfrow_data)must be implemented in child class pass text format for table class textformat(tableformat)""text format for table "" option for modifying width def __init__(selfwidth= out_file=none)override init inherit parent init as well to save data in file super(__init__(out_fileself width width def heading(selfheader)print headers for in headerprint("{ :>{ } }format(hself width)end='file=self out_fileprint(file=self out_file def row(selfrow_data)print rows for in row_dataprint("{ :>{ } }format(rself width)end='file=self out_fileprint(file=self out_file csv format for table class csvformat(tableformat)""text format for table "" init will be inherited from parent to save data in file def heading(selfheader)print headers print(',join(header)file=self out_file def row(selfrow_data)print rows print(",join(row_data)file=self out_file(continues on next page advance inheritance
4,481
(continued from previous page put quotes around data this class will be used with other class in mixin class quotedata(object)def row(selfrow_data)quoted_data ['"{ }"format(rfor in row_datasuper(row(quoted_datanature of super(is decided by child class mixin quotedata and csvformat this will decide the nature of super(in quotedata class mixinquotecsv(quotedatacsvformat)pass mixin quotedata and textformat class mixinquotetext(quotedatatextformat)pass this code is copied from datamine py file and modified slightly to include the type of the data def read_file(filenametypesmode='warn')''read csv file and save data in the list '' check for correct mode if mode not in ['warn''silent''stop']raise valueerror("possible modes are 'warn''silent''stop'" ring_data [create empty list to save data with open (filename' 'as frows csv reader(fheader next(rowsskip the header change the types of the columns for row in rowstryrow[ float(row[ ]radius row[ float(row[ ]price row[ int(row[ ]quantity generalized conversion row [d_type(valfor d_typeval in zip(typesrow)except valueerror as errprocess value error only if mode ='warn'print("invalid datarow is skipped"print('row{}reason {}format(row_numerr)elif mode ='silent'pass do nothing elif mode ='stop'raise raise the exception continue ring_data append(tuple(row) append data in list in the form of tuple row_dict 'daterow[ ]'metalrow[ ]'radiusrow[ ]'pricerow[ ]'quantityrow[ (continues on next page advance inheritance
4,482
(continued from previous page row_dict ring(row[ ]row[ ]row[ ]row[ ]row[ ]use below or above line row_dict ringdate row[ ]metal row[ ]radius row[ ]price row[ ]quantity row[ ring_data append(row_dict return ring_data table formatter def print_table(list_namecol_name=['metal''radius']out_format=textformat(out_file=none))note that class is passed here ""print the formatted output "" for in col_nameprint header print("{:> }format( )end='print(print empty line for in list_nameprint values for in col_nameprint("{:> }format(str(getattr(lc)))end='print( invoke class-method for printing heading out_format heading(col_nameclass is passed to out_format for in list_namestore row in list row_data [str(getattr(lc)for in col_nameout_format row(row_datapass rows to class-method row( def main()list correct types of columns in csv file types =[strstrfloatfloatint read file and save data in list list_data read_file('price csv'types formatted output print_table(list_dataprint(print_table(list_data['metal''radius''price']out_format=textformat() print in file out_file open("text_format txt"" "open file in write mode print_table(list_data['metal''radius''price']out_format=textformat(out_file=out_file)out_file close( print in file with width out_file open("wide_text_format txt"" "open file in write mode print_table(list_data['metal''radius''price']out_format=textformat(width= out_file=out_file)(continues on next page advance inheritance
4,483
(continued from previous page out_file close( print(print_table(list_data['metal''radius''price']out_format=csvformat()print in file out_file open("csv_format csv"" "open file in write mode print_table(list_data['metal''radius''price']out_format=csvformat(out_file=out_file)out_file close( print_table(list_data['metal''radius''price']out_format=mixinquotetext() print(print_table(list_data['metal''radius''price']out_format=mixinquotecsv() if __name__ ='__main__'main( conclusion in this we saw some of the oops feature of python especially inheritance more examples of inheritance are included in we discussed some of the differences between python and other programming language in next we will discuss '@propertyand 'descriptoretc alsoin the next we will discuss some more differences between python and other programming language conclusion
4,484
methods and @property introduction in this we will understand the usage of 'methods''@propertyand 'descriptor methodsstaticmethod and classmethod in previous we saw the examples of methodse 'areaand 'costin listing inside the class without any decorator with them the 'decoratorsadds the additional functionality to the methodsand will be discussed in details in in this sectionwe will quickly review the different types of methods with an example then these methods will be used with our previous examples in the below codetwo decorators are used with the methods inside the class 'staticmethodand 'classmethodplease see the comments and noticehow do the different methods use different values of for adding two numbersnotewe can observe the following differences in these three methods from the below codemethod it uses the instance variable (self xfor additionwhich is set by __init__ function classmethod it uses class variable for addition staticmethod it uses the value of which is defined in main program ( outside the class if is not definedthen nameerror will be generated mehodsex py below will be used by static method if we do not define itthe staticmethod will generate error class add(object) class variable def __init__(selfx)self instance variable def addmethod(selfy)print("method:"self @classmethod as conventioncls must be used for classmethodinstead of self (continues on next page
4,485
(continued from previous pagedef addclass(selfy)print("classmethod:"self @staticmethod def addstatic( )print("staticmethod:" ydef main()method add( = or add( for methodabove will be used for addition addmethod( method classmethod add( for class methodclass variable will be used for addition addclass( clasmethod for static methodx= (at the top of file)will be used for addition add( addstatic( staticmethod if __name__ ='__main__'main(below is the output for above codepython methodex py method classmethod staticmethod research organization in previous we had two users who are modifying the class attributes first was the mathematician (mathematician py)who is modifying the 'radiusin listing and other is the box companywho were modifying the method 'perimeterin listing lastlywe had contributor who is creating 'table formatterin listing for displaying the output nicely nowwe have another research organizationwho were doing their research analysis based on the diameters (not using radius)therefore they want to initialize the class-objects based on the diameter directly noteif we change the the 'radiusto 'diameterin the __init__ function of class ringthen we need to modify the 'areaand 'costmethods as well alsothe codes of other users (mathematician and box companywill break but we can solve this problem using 'classmethodas shown next multiple constructor using 'classmethodthe 'classmethodis very useful tools to create the multiple constructor as shown in the below listing research organization
4,486
pythonic py import math import time class ring(object)""here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology "" class variables date time strftime("% -% -% "time gmtime()today' date "yyyy-mm-ddcenter center of the ring def __init__(selfdate=datemetal="copper"radius= price= quantity= )""init is not the constructorbut the initializer which initialize the instance variable self is the instance __init__ takes the instance 'selfand populates it with the radiusmetaldate etc and store in dictionary self radiusself metal etc are the instance variable which must be unique "" self date date self metal metal self radius radius self price price self quantity quantity multiple constructor below constructor is added for the 'research organizationwho are doing their work based on diameters@classmethod def diameter_init(clsdiameter)radius diameter/ change diameter to radius return cls(radiusreturn radius def cost(self)return self price self quantity def area(self)return math pi self radius** def perimeter(self)return math pi self radius def main()print("center of the ring is at:"ring centermodify class variable ring(price= modify only price print("radius:{ }cost:{ }format( radiusr cost())print("radius:{ }perimeter:{ : }format( radiusr perimeter()) print(check the new constructor 'diameter_initd ring diameter_init(diameter= (continues on next page research organization
4,487
(continued from previous page print("radius:{ }perimeter:{ : }format( radiusd perimeter()) if __name__ ='__main__'main(following are the outputs for above codepython pythonic py center of the ring is at radius: cost: radius: perimeter: radius: perimeter: additional methods using 'staticmethodnowthe research organization wants one more features in the classi meter to centimeter conversion note that this feature has no relation with the other methods in the class in the other wordsthe output of meter to centimeter conversion will not be used anywhere in the classbut it' handy for the organization to have this feature in the package in such caseswe can use static methods notethere is no point to create 'meter_cmmethod as 'meter_cm(selfmeter)and store it in the dictionaryas we are not going to use it anywhere in the class we added this to meet the client' requirement onlyhence it should be added as simple definition (not as methods)which can be done using @staticmethod in the other wordsstatic methods are used to attached functions to classes pythonic py import math import time class ring(object)""here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology "" class variables date time strftime("% -% -% "time gmtime()today' date "yyyy-mm-ddcenter center of the ring def __init__(selfdate=datemetal="copper"radius= price= quantity= )""init is not the constructorbut the initializer which initialize the instance variable self is the instance __init__ takes the instance 'selfand populates it with the radiusmetaldate etc and store in dictionary self radiusself metal etc are the instance variable which must be unique ""(continues on next page research organization
4,488
(continued from previous page self date date self metal metal self radius radius self price price self quantity quantity multiple constructor below constructor is added for the 'research organizationwho are doing their work based on diameters@classmethod def diameter_init(clsdiameter)radius diameter/ change diameter to radius return cls(radiusreturn radius @staticmethod meter to centimeter conversion def meter_cm(meter)return( *meter def cost(self)return self price self quantity def area(self)return math pi self radius** def perimeter(self)return math pi self radius def main()print("center of the ring is at:"ring centermodify class variable ring(price= modify only price print("radius:{ }cost:{ }format( radiusr cost())print("radius:{ }perimeter:{ : }format( radiusr perimeter()) print(check the new constructor 'diameter_initd ring diameter_init(diameter= print("radius:{ }perimeter:{ : }format( radiusd perimeter()) meter print("{ meter { centimeterformat(md meter_cm( )) if __name__ ='__main__'main(following is the output of above codepython pythonic py center of the ring is at radius: cost: radius: perimeter: radius: perimeter: meter centimeter micro-managing micro-managing is the methodwhere client tells us the ways in which the logic should be implemented lets understand it by an example micro-managing
4,489
notenow the research organization wants that the 'areashould be calculated based on the 'perimetermore specificallythey will provide the 'diameter'then we need to calculate the 'perimeter'then based on the 'perimeter'calculate the 'radiusand finally calculate the 'areabased on this new radius this may look sillybut if we look closelythe radius will change slightly during this conversion processas there will be some difference between (diameter/ and (math pi*diameter)/ *math pithe reason for difference ison computer we do not cancel the math pi at numerator with math pi at denominatorbut solve the numerator first and then divide by the denominatorand hence get some rounding errors wrong solution the solution to this problem may look pretty simplei modify the 'areamethod in the following way pythonic py import math import time class ring(object)""here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology "" class variables date time strftime("% -% -% "time gmtime()today' date "yyyy-mm-ddcenter center of the ring def __init__(selfdate=datemetal="copper"radius= price= quantity= )""init is not the constructorbut the initializer which initialize the instance variable self is the instance __init__ takes the instance 'selfand populates it with the radiusmetaldate etc and store in dictionary self radiusself metal etc are the instance variable which must be unique "" self date date self metal metal self radius radius self price price self quantity quantity multiple constructor below constructor is added for the 'research organizationwho are doing their work based on diameters@classmethod def diameter_init(clsdiameter)radius diameter/ change diameter to radius return cls(radiusreturn radius @staticmethod meter to centimeter conversion (continues on next page micro-managing
4,490
(continued from previous page def meter_cm(meter)return( *meter def cost(self)return self price self quantity def area(self)return math pi self radius** self perimeter(calculate perimeter math pireturn math pi ** def perimeter(self)return math pi self radius def main()print("center of the ring is at:"ring centermodify class variable ring(price= modify only price print("radius:{ }cost:{ }format( radiusr cost())print("radius:{ }perimeter:{ : }format( radiusr perimeter()) print(check the new constructor 'diameter_initd ring diameter_init(diameter= print("radius:{ }perimeter:{ : }area:{ : }formatd radiusd perimeter() area())print("radius:{ }perimeter:{ : }format( radiusd perimeter()) meter print("{ meter { centimeterformat(md meter_cm( )) if __name__ ='__main__'main(if we run the above codewe will have the following resultswhich is exactly right python pythonic py radius: perimeter: area: errorabove solution looks pretty simplebut it will break the code in 'box py in listing 'as it is modifying the perimeter by factor of by overriding the perimeter method thereforefor calculating the area in box py filepython interpretor will use the child class method 'perimeterfor getting the value of perimeter hencethe area will be calculated based on the 'modified parameter'not based on actual parameter in box pythe area will be wrongly calculatedbecause it is modifying the perimeter for their usage nowradius will be calculated by new perimeter (as they override the perimeter methodand finally area will be modified due to change in radius valuesas shown belowfrom box import box diameter_init( radius perimeter(doubled value of perimeter (desired area(wrong value of areasee next for correct result import math math pi radius** desired radius math pi ( perimeter()/( *math pi))** calculated radius micro-managing
4,491
correct solution notethe above problem can be resolved by creating local copy of perimeter in the class in this waythe child class method can not override the local-copy of parent class method for thiswe need to modify the code as below pythonic py import math import time class ring(object)""here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology "" class variables date time strftime("% -% -% "time gmtime()today' date "yyyy-mm-ddcenter center of the ring def __init__(selfdate=datemetal="copper"radius= price= quantity= )""init is not the constructorbut the initializer which initialize the instance variable self is the instance __init__ takes the instance 'selfand populates it with the radiusmetaldate etc and store in dictionary self radiusself metal etc are the instance variable which must be unique "" self date date self metal metal self radius radius self price price self quantity quantity multiple constructor below constructor is added for the 'research organizationwho are doing their work based on diameters@classmethod def diameter_init(clsdiameter)radius diameter/ change diameter to radius return cls(radiusreturn radius @staticmethod meter to centimeter conversion def meter_cm(meter)return( *meter def cost(self)(continues on next page micro-managing
4,492
(continued from previous page return self price self quantity def area(self)return math pi self radius** self perimeter(wrong way to calculate perimeter self _perimeter(use local copy of perimeter( math pireturn math pi ** def perimeter(self)return math pi self radius local copy can be created in the lines after the actual method _perimeter perimeter make local copy of perimeter def main()print("center of the ring is at:"ring centermodify class variable ring(price= modify only price print("radius:{ }cost:{ }format( radiusr cost())print("radius:{ }perimeter:{ : }format( radiusr perimeter()) print(check the new constructor 'diameter_initd ring diameter_init(diameter= print("radius:{ }perimeter:{ : }area:{ : }formatd radiusd perimeter() area())print("radius:{ }perimeter:{ : }format( radiusd perimeter()) meter print("{ meter { centimeterformat(md meter_cm( )) if __name__ ='__main__'main(below is the result for above listingpython pythonic py radius: perimeter: area: nowwe will get the correct results for the 'box pyas wellas shown belowfrom box import box diameter_init( radius perimeter(doubled value of perimeter (desired area(desired area private attributes are not for privatizing the attributes in section we saw that there is no concept of data-hiding in pythonand the attributes can be directly accessed by the the clients notethere is misconception that the double underscore ('__'are used for data hiding in python in this sectionwe will see the correct usage of '__in python private attributes are not for privatizing the attributes
4,493
same local copy in child and parent class in previous sectionwe made local copy of method 'perimeteras '_perimeterin this waywe resolve the problem of overriding the parent class method butif the child class ( box pymakes local copy the perimeter as well with the same name _perimeterthen we will again have the same problemas shown below box py user- creating boxes for the ring from pythonic import ring class box(ring)""modified perimeter for creating the box "" def perimeter(self)override the method 'perimeterperimeter is increased times return ring perimeter(self _perimeter perimeter def main() box(radius= pass radius print("radius:" radiusprint("modified perimeter% perimeter()( *pi*radius if __name__ ='__main__'main(nowwe will have same problem as beforefrom box import box diameter_init( area(wrong value of area again use '__perimeterinstead of '_perimeterto solve the problem the above problem can be solved using double underscore before the perimeter instead of one underscoreas shown belowfirst replace the _perimeter with __ perimeter in the 'pythonic pyas below pythonic py import math import time class ring(object)""here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology "" class variables date time strftime("% -% -% "time gmtime()today' date "yyyy-mm-ddcenter center of the ring def __init__(selfdate=datemetal="copper"radius= (continues on next page private attributes are not for privatizing the attributes
4,494
(continued from previous page price= quantity= )""init is not the constructorbut the initializer which initialize the instance variable self is the instance __init__ takes the instance 'selfand populates it with the radiusmetaldate etc and store in dictionary self radiusself metal etc are the instance variable which must be unique "" self date date self metal metal self radius radius self price price self quantity quantity multiple constructor below constructor is added for the 'research organizationwho are doing their work based on diameters@classmethod def diameter_init(clsdiameter)radius diameter/ change diameter to radius return cls(radiusreturn radius @staticmethod meter to centimeter conversion def meter_cm(meter)return( *meter def cost(self)return self price self quantity def area(self)return math pi self radius** self perimeter(wrong way to calculate perimeter self __perimeter(use local copy of perimeter( math pireturn math pi ** def perimeter(self)return math pi self radius local copy can be created in the lines after the actual method __perimeter perimeter make local copy of perimeter def main()print("center of the ring is at:"ring centermodify class variable ring(price= modify only price print("radius:{ }cost:{ }format( radiusr cost())print("radius:{ }perimeter:{ : }format( radiusr perimeter()) print(check the new constructor 'diameter_initd ring diameter_init(diameter= print("radius:{ }perimeter:{ : }area:{ : }formatd radiusd perimeter() area())print("radius:{ }perimeter:{ : }format( radiusd perimeter()) meter print("{ meter { centimeterformat(md meter_cm( ))(continues on next page private attributes are not for privatizing the attributes
4,495
(continued from previous page if __name__ ='__main__'main(next replace the _perimeter with __ perimeter in the 'box pyas below box py user- creating boxes for the ring from pythonic import ring class box(ring)""modified perimeter for creating the box "" def perimeter(self)override the method 'perimeterperimeter is increased times return ring perimeter(self __perimeter perimeter def main() box(radius= pass radius print("radius:" radiusprint("modified perimeter% perimeter()( *pi*radius if __name__ ='__main__'main(important_ is not designed for making the attribute privatebut for renaming the attribute with class name to avoid conflicts due to same name as we see in above examplewhere using same name _perimeter in both parent and child class resulted in the wrong answer if we use _perimeter instead of _perimeterthen _perimeter will be renamed as _classname__perimeter thereforeeven parent and child class uses the same name with two underscorethe actual name will be differed because python interpretor will add the classname before those nameswhich will make it different from each other nowwe have same name in both the files __perimeterbut problem will no longer occur as the 'class-nameswill be added by the python before __perimeter below is the result for both the python filespython pythonic py radius: perimeter: area: from box import box diameter_init( area( notethere is no notion of private attributes in python all the objects are exposed to users butsingle underscore before the method or variable indicates that the attribute should not be access directly is designed for freedom not for privacy as we saw in this section private attributes are not for privatizing the attributes
4,496
@property nowwe will see the usage of @property in python managing attributes currentlywe are not checking the correct types of inputs in our design let' see our 'pythonic pyfile again from pythonic import ring( radius radius "meher radius 'mehermehernote that in the above codethe string is saved in the radiusand the multiplication is performed on the string we do not want this behaviortherefore we need to perform some checks before saving data in the dictionarywhich can be done using @propertyas shown belowimportant@property decorator allows operator to call the function hereself radius will call the method radiuswhich returns the self _radius hence_radius is stored in the dictionary instead of dict if we use 'return self radiusinstead of 'return self _radius'then the @property will result in infinite loop as self property will call the property methodwhich will return self propertywhich results in calling the @property again furtherwe can use @property for type checkingvalidation or performing various operations by writing codes in the setter method change the date to todays date etc pythonic py import math import time class ring(object)""here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology "" class variables date time strftime("% -% -% "time gmtime()today' date "yyyy-mm-ddcenter center of the ring def __init__(selfdate=datemetal="copper"radius= price= quantity= )""init is not the constructorbut the initializer which initialize the instance variable self is the instance __init__ takes the instance 'selfand populates it with the radiusmetaldate etc and store in dictionary self radiusself metal etc are the instance variable which must be unique (continues on next page @property
4,497
(continued from previous page "" self date date self metal metal self radius radius self price price self quantity quantity @property method-name should be same as attribute 'radiushere def radius(self)return self _radius _radius can be changed with other name @radius setter def radius(selfval)'valshould be float or int if not isinstance(val(floatint))raise typeerror("expectedfloat or int"self _radius float(val multiple constructor below constructor is added for the 'research organizationwho are doing their work based on diameters@classmethod def diameter_init(clsdiameter)radius diameter/ change diameter to radius return cls(radiusreturn radius @staticmethod meter to centimeter conversion def meter_cm(meter)return( *meter def cost(self)return self price self quantity def area(self)return math pi self radius** self perimeter(wrong way to calculate perimeter self __perimeter(use local copy of perimeter( math pireturn math pi ** def perimeter(self)return math pi self radius local copy can be created in the lines after the actual method __perimeter perimeter make local copy of perimeter def main()print("center of the ring is at:"ring centermodify class variable ring(price= modify only price print("radius:{ }cost:{ }format( radiusr cost())print("radius:{ }perimeter:{ : }format( radiusr perimeter()) print(check the new constructor 'diameter_initd ring diameter_init(diameter= print("radius:{ }perimeter:{ : }area:{ : }formatd radiusd perimeter() area())print("radius:{ }perimeter:{ : }format( radiusd perimeter()) meter print("{ meter { centimeterformat(md meter_cm( ))(continues on next page @property
4,498
(continued from previous page if __name__ ='__main__'main(below is the results for above codefrom pythonic import ring( radius radius radius radius radius radius "mehertraceback (most recent call last)typeerrorexpectedfloat or int below is the dictionary of the object 'rof code note thatthe 'radiusdoes not exist there anymorebut this will not break the codes of other usersdue to following reason note@property is used to convert the attribute access to method access in the other wordsthe radius will be removed from instance variable list after defining the 'propertyas in above code nowit can not be used anymore but@property decorator will convert the attribute access to method accessi the dot operator will check for methods with @property as well in this waythe code of other user will not break __dict__ {'date''''metal''copper''_radius' 'price' 'quantity' calling method as attribute if method is decorated with @property then it can be called as 'attributeusing operatorbut then it can not be called as attributeas shown in below exampleclass propertex(object)def mes_ (self)print("hello msg_ "@property def mes_ (self)can be called as attribute only print("hello msg_ " propertex( mes_ (hello msg_ mes_ hello msg_ mes_ (can not be called as method hello msg_ traceback (most recent call last)file ""line in typeerror'nonetypeobject is not callable @property
4,499
requirement from research organization nowwe get another rule from the research organization as belowwe do not want to store radius as instance variableinstead convert radius into diameter and save it as instance variable in the dictionary notethis condition will raise following two problemsmain problem here is thatother users already started using this class and have access to attribute 'radiusnowif we replace the key 'radiuswith 'diameter'then their code will break immediately alsowe need to update all our code as everything is calculated based on radiusand we are going to remove these attribute from diameter this is the main reason for hiding attributes in java and ++as these languages have no easy solution for this hencethese languages use getter and setter method but in python this problem can be solved using @property @property is used to convert the attribute access to method access in the other wordsas radius will be removed from instance variable list after meeting the need of the organizationtherefore it can not be used anymore but@property decorator will convert the attribute access to method accessi the dot operator will check for methods with @property as well in this waythe codes of other users will not breakas shown next pythonic py import math import time class ring(object)""here we will see the actual logic behind various pieces of python language instancesvariablesmethod and @property etc alsowe will see the combine usage of these pieces to complete design with agile methodology "" class variables date time strftime("% -% -% "time gmtime()today' date "yyyy-mm-ddcenter center of the ring def __init__(selfdate=datemetal="copper"radius= price= quantity= )""init is not the constructorbut the initializer which initialize the instance variable self is the instance __init__ takes the instance 'selfand populates it with the radiusmetaldate etc and store in dictionary self radiusself metal etc are the instance variable which must be unique "" self date date self metal metal self radius radius self price price self quantity quantity (continues on next page @property