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 'format...
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 num...
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 \"...
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 ...
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 csv...
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 ...
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 strin...
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 column...
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 out...
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"'' '' '' 'note...
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...
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 ther...
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...
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[ ...
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 cr...
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 compari...
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 usi...
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...
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 i...
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 ...
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[ :...
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 assignm...
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 th...
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 ...
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 lju...
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(' ' ...
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 obj...
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 {'nam...
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' item...
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 t...
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 ...
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 co...
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(li...
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 an...
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...
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__(selfn...
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 o...
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 _...
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 fo...
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_...
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...
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 ...
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 wit...
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 thre...
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 c...
4,446
(continued from previous page+-isadirectoryerror +-notadirectoryerror +-permissionerror +-processlookuperror +-timeouterror +-referenceerror +-runtimeerror +-notimplementederror +-recursionerror +-syntaxerror +-indentationerror +-taberror +-systemerror +-typeerror +-valueerror +-unicodeerror +-unicodedecodeerror +-unic...
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 p...
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[ f...
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 fi...
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("t...
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['p...
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' 'pr...
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...
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 ca...
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...
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 objec...
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...
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 cl...
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 ...
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 ge...
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 value...
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 th...
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("{:> }...
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 gm...
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 suc...
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 inherit...
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...
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()( *p...
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 ch...
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[ ]'qua...
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 rad...
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 tabl...
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(l...
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 clas...
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 ...
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 errpr...
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 =[strs...
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 pr...
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 belowi...
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...
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(i...
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))...
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''...
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 ...
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 sta...
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 g...
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 organizatio...
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...
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 ...
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 ...
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...
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 ac...
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 pro...
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 mu...
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 incr...
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 m...
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 in...
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 ...
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 thatoth...