id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
8,800 | which in the case of the item access operator are __getitem__()__setitem__()and __delitem__(the image class uses html-style hexadecimal strings to represent colors the background color must be set when the image is createdotherwiseit defaults to white the image class saves and loads images in its own custom formatbut i... |
8,801 | object-oriented programming @property def width(self)return self __width @property def height(self)return self __height @property def colors(self)return set(self __colorscopying collections when returning data attribute from an object we need to be aware of whether the attribute is of an immutable or mutable type it is... |
8,802 | table collection special methods special method usage description __contains__(selfxx in returns true if is in sequence or if is key in mapping __delitem__(selfkdel [kdeletes the -th item of sequence or the item with key in mapping __getitem__(selfky[kreturns the -th item of sequence or the value for key in mapping __i... |
8,803 | object-oriented programming if coordinate' color is deleted the effect is to make that coordinate' color the background color again we use dict pop(to remove the item since it will work correctly whether or not an item with the given coordinate is in the dictionary both __setitem__(and __delitem__(have the potential to... |
8,804 | object-oriented programming we had to open the file in binary mode when reading pickles no protocol is specified--the pickle load(function is smart enough to work out the protocol for itself def load(selffilename=none)if filename is not noneself filename filename if not self filenameraise nofilenameerror(fh none tryfh ... |
8,805 | __export_xpm(method because it isn' really relevant to this themebut it is in the book' source codeof course we have now completed our coverage of the custom image class this class is typical of those used to hold program-specific dataproviding access to the data items it containsthe ability to save and load all its da... |
8,806 | object-oriented programming str(letters="[' '' '' '' '' '' '' '' ']letters[ returns'ca sortedlist object aggregates (is composed oftwo private attributesa functionself __key((held as object reference self __key)and listself __list lambda functions the key function is passed as the second argument (or using the key keyw... |
8,807 | more obvious alternative would have been self __key key if key is not none else _identity once we have the key functionwe use an assert to ensure that it is callable the built-in hasattr(function returns true if the object passed as its first argument has the attribute whose name is passed as its second argument there ... |
8,808 | object-oriented programming def __bisect_left(selfvalue)key self __key(valueleftright len(self __listwhile left rightmiddle (left right/ if self __key(self __list[middle]keyleft middle elseright middle return left this private method calculates the index position where the given value belongs in the listthat isthe inde... |
8,809 | del self __list[indexcount + return count this method is similar to the sortedlist remove(methodand is an extension of the list api it starts off by finding the index position where the first occurrence of the value belongs in the listand then loops as long as the index position is within the list and the item at the i... |
8,810 | object-oriented programming def __setitem__(selfindexvalue)raise typeerror("use add(to insert value and rely on "the list to put it in the right place"we don' want the user to change an item at given index position (so [nx is disallowed)otherwisethe sorted list' order might be invalidated the typeerror exception is the... |
8,811 | the sortedlist clear(method discards the existing list and replaces it with new empty list the sortedlist pop(method removes and returns the item at the given index positionor raises an indexerror exception if the index is out of range for the pop()__len__()and __str__(methodswe simply pass on the work to the aggregate... |
8,812 | object-oriented programming creating collection classes using inheritance collections ordereddict |the sorteddict class shown in this subsection attempts to mimic dict as closely as possible the major difference is that sorteddict' keys are always ordered based on specified key function or on the identity function sort... |
8,813 | we keep copy of all the dictionary' keys in sorted list stored in the self __keys variable we pass the dictionary' keys to initialize the sorted list using the base class' dict keys(method--we must not use sorteddict keys(because that relies on the self __keys variable which will exist only after the sortedlist of keys... |
8,814 | object-oriented programming the dict api includes the dict fromkeys(class method this method is used to create new dictionary based on an iterable each element in the iterable becomes keyand each key' value is either none or the specified value because this is class method the first argument is provided automatically b... |
8,815 | generator functions generator function or generator method is one which contains yield expression when generator function is called it returns an iterator values are extracted from the iterator one at time by calling its __next__(method at each call to __next__(the generator function' yield expression' value (none if n... |
8,816 | object-oriented programming def pop(selfkey*args)if key not in selfif len(args= raise keyerror(keyreturn args[ self __keys remove(keyreturn super(pop(keyargsif the given key is in the dictionary this method returns the corresponding value and removes the key-value item from the dictionary the key must also be removed f... |
8,817 | dictionaries have four methods that return iteratorsdict values(for the dictionary' valuesdict items(for the dictionary' key-value itemsdict keys(for the keysand the __iter__(special method that provides support for the iter(dsyntaxand operates on the keys (actuallythe base class versions of these methods return dictio... |
8,818 | object-oriented programming the base class methods dict get()dict __getitem__((for the [ksyntax)dict __len__((for len( ))and dict __contains__((for in dall work fine as they are and don' affect the key orderingso we have not needed to reimplement them the last dict method that we must reimplement is copy(def copy(self)... |
8,819 | erator ([]applied directly to selfsince self is dict if an out-of-range index is given the methods raise an indexerror exception we have now completed the implementation of the sorteddict class it is not often that we need to create complete generic collection classes like thisbut when we dopython' special methods allo... |
8,820 | object-oriented programming we learned that object creation and initialization are separate operations and that python allows us to control bothalthough in almost every case we only need to customize initialization we also learned that although it is always safe to return an object' immutable data attributeswe should n... |
8,821 | exercises ||the first two exercises involve modifying classes we covered in this and the last two exercises involve creating new classes from scratch modify the point class (from shape py or shapealt py)to support the following operationswhere pqand are points and is numberp + - * / / // point __add__(point __iadd__(po... |
8,822 | object-oriented programming ertythe name should be read-write property with an assertion to ensure that the name is at least four characters long the class should support the built-in len(function (returning the number of transactions)and should provide two calculated read-only propertiesbalance which should return the... |
8,823 | writing and reading binary data writing and parsing text files writing and parsing xml files random access binary files |||file handling most programs need to save and load informationsuch as data or state informationto and from files python provides many different ways of doing this we already briefly discussed handli... |
8,824 | file handling name data type notes minimum length and no whitespace report_id str date datetime date airport str nonempty and no newlines aircraft_id str nonempty and no newlines aircraft_type str nonempty and no newlines pilot_percent_hours_on_type float range to pilot_total_hours int positive and nonzero midair bool ... |
8,825 | format reader/writer reader writer lines of code total lines of code output file size (~kbbinary pickle (gzip compressed binary pickle binary manual (gzip compressed binary manual plain text regex reader/manual writer plain text manual xml element tree xml dom xml sax reader/manual writer figure aircraft incident file ... |
8,826 | file handling reads aircraft incident data from infile and writes the data to outfile the data formats used depend on the file extensionsaix is xmlait is text (utf- encoding)aib is binaryaip is pickleand html is html (only allowed for the outfileall formats are platform-independent options- --help show this help messag... |
8,827 | self pilot_total_hours pilot_total_hours self midair midair self narrative narrative the report id is validated when the incident is created and is available as the read-only report_id property all the other data attributes are read/write properties for examplehere is the date property' code@property def date(self)retu... |
8,828 | the bytes and bytearray data types python provides two data types for handling raw bytesbytes which is immutableand bytearray which is mutable both types hold sequence of zero or more -bit unsigned integers (byteswith each byte in the range str translate( both types are very similar to strings and provide many of the s... |
8,829 | file handling if compression has been requestedwe use the gzip module' gzip open(function to open the fileotherwisewe use the built-in open(function we must use "write binarymode ("wb"when pickling data in binary format in python and pickle highest_protocol is protocol compact binary pickle format this is the best prot... |
8,830 | def import_pickle(selffilename)fh none tryfh open(filename"rb"magic fh read(len(gzip_magic)if magic =gzip_magicfh close(fh gzip open(filename"rb"elsefh seek( self clear(self update(pickle load(fh)return true except (environmenterrorpickle unpicklingerroras errprint("{ }import error{ }formatos path basename(sys argv[ ])... |
8,831 | file handling when creating custom binary file formats it is wise to create magic number to identify your file typeand version number to identify the version of the file format in use here are the definitions used in the convert-incidents py programmagic "aib\ format_version "\ \ we have used four bytes for the magic n... |
8,832 | the struct module the struct module provides struct pack()struct unpack()and some other functionsand the struct struct(class the struct pack(function takes struct format string and one or more values and returns bytes object that holds all the values represented in accordance with the format the struct unpack(function ... |
8,833 | file handling "en wikipedia org"the format will be "< (little-endian byte order -byte unsigned integer -byte byte string)and the bytes object that is returned will be '\ \ en wikipedia orgconvenientlypython shows bytes objects in compact form using printable ascii characters where possibleand hexadecimal escapes (and s... |
8,834 | table bytes and bytearray methods # syntax description ba append(iappends int (in range to bytearray ba capitalize(returns copy of bytes/bytearray with the first character capitalized (if it is an ascii letterb center(widthbytereturns copy of centered in length width padded with spaces or optionally with the given byte... |
8,835 | file handling table bytes and bytearray methods # syntax description istitle(returns true if is nonempty and title-cased isupper(returns true if has at least one uppercaseable ascii character and all its uppercaseable characters are uppercase join(seqreturns the concatenation of every bytes/bytearray in sequence seqwit... |
8,836 | table bytes and bytearray methods # syntax description upper(returns an ascii-uppercased copy of bytes/bytearray zfill(wreturns copy of bwhich if shorter than is padded with leading zeros ( charactersto make it bytes long we have omitted the except and finally blocks since they are the same as the ones shown in the pre... |
8,837 | nar dat pil hou t_pe rs_ rce on_ nt_ typ pil hou t_to tal rs mid string string string string uint float int bool ive typ rat ft_ cra por uint air air cra ft_ id string air file handling rep ort _id utf- encoded bytes figure the structure of binary aircraft incident record def import_binary(selffilename)def unpack_strin... |
8,838 | must read to get the string if the length is zero we simply return an empty string otherwisewe attempt to read the specified number of bytes if we don' get any data or if the data is not the size we expected ( it is too little)we raise valueerror exception if we have the right number of bytes we create suitable format ... |
8,839 | file handling while truereport_id unpack_string(fhfalseif report_id is nonebreak data {data["report_id"report_id for name in ("airport""aircraft_id""aircraft_type""narrative")data[nameunpack_string(fhother_data fh read(numbersstruct sizenumbers numbersstruct unpack(other_datadata["date"datetime date fromordinal(numbers... |
8,840 | writing and parsing text files ||writing text is easybut reading it back can be problematicso we need to choose the structure carefully so that it is not too difficult to parse figure shows an example aircraft incident record in the text format we are going to use when we write the incident records to file we will foll... |
8,841 | file handling fh none tryfh open(filename" "encoding="utf "for incident in self values()narrative "\njoin(wrapper wrapincident narrative strip())fh write("[{ report_id}]\ "date={ date! }\ "aircraft_id={ aircraft_id}\ "aircraft_type={ aircraft_type}\ "airport={airport}\ "pilot_percent_hours_on_type="{ pilot_percent_hour... |
8,842 | parsing text |the method for reading and parsing text format aircraft incident records is longer and more involved than the one used for writing when reading the file we could be in one of several states we could be in the middle of reading narrative lineswe could be at key=value lineor we could be at report id line at... |
8,843 | file handling the lineand if this leaves us with an empty line (and providing we are not in the middle of narrative)we simply skip to the next line this means that the number of blank lines between incidents doesn' matterbut that we preserve any blank lines that are in narrative texts if the narrative is not none we kn... |
8,844 | if we are not in narrative and are not reading new report id there are only three more possibilitieswe are reading key=value itemswe are at narrative start markeror something has gone wrong in the case of reading line of key=value datawe split the line on the first characterspecifying maximum of one split--this means t... |
8,845 | file handling message for the userand returns false and no matter whatif the file was openedit is closed at the end parsing text using regular expressions |readers unfamiliar with regular expressions ("regexes"are recommended to read before reading this section--or to skip ahead to the following section )and return her... |
8,846 | the incident record the re multiline flag means that in this regular expression matches at the start of every line (rather than just at the start of the string)and matches at the end of every line (rather than just at the end of the string)so the narrative start and end markers are matched only at the start of lines th... |
8,847 | file handling from each match of the incident_re regular expression we then extract all the key=value strings in one go using the keyvalues match groupand apply the key_value_re regular expression' re finditer(method to iterate over each individual key=value line for each (keyvaluepair foundwe put them in the data dict... |
8,848 | <incident report_id=" gdate="aircraft_id=" aircraft_type="ce- -mpilot_percent_hours_on_type=" pilot_total_hours=" midair=" "bowerman on go-around from night crosswind landing attempt the aircraft hit runway edge light damaging one propeller figure an example xml format aircraft incident record in context treedomand sax... |
8,849 | file handling midair=str(int(incident midair))airport xml etree elementtree subelement(element"airport"airport text incident airport strip(narrative xml etree elementtree subelement(element"narrative"narrative text incident narrative strip(root append(elementtree xml etree elementtree elementtree(rootwe begin by creati... |
8,850 | reading an xml file using an element tree is not much harder than writing one again there are two phasesfirst we read and parse the xml fileand then we traverse the resultant element tree to read off the data to populate the incidents dictionary again this second phase is not necessary if the element tree itself is bei... |
8,851 | file handling once we have the element tree we can iterate over every using the xml etree elementtree findall(method each incident is returned as an xml etree element object we use the same technique for handling the element attributes as we did in the previous section' import_text_regex(method--first we store all the ... |
8,852 | ("pilot_total_hours"str(incident pilot_total_hours))("midair"str(int(incident midair))))element setattribute(attributevaluefor nametext in (("airport"incident airport)("narrative"incident narrative))text_element tree createtextnode(textname_element tree createelement(namename_element appendchild(text_elementelement app... |
8,853 | file handling port_xml_dom(function in three partsstarting with the def line and the nested get_text(function def import_xml_dom(selffilename)def get_text(node_list)text [for node in node_listif node nodetype =node text_nodetext append(node datareturn "join(textstrip(the get_text(function iterates over list of nodes ( ... |
8,854 | data["airport"get_text(airport childnodesnarrative element getelementsbytagname"narrative")[ data["narrative"get_text(narrative childnodesincident incident(**dataself[incident report_idincident except (valueerrorlookuperrorincidenterroras errprint("{ }import error{ }formatos path basename(sys argv[ ])err)return false r... |
8,855 | file handling for incident in self values()fh write('<incident report_id={report_id'date="{ date! }'aircraft_id={aircraft_id'aircraft_type={aircraft_type'pilot_percent_hours_on_type='"{ pilot_percent_hours_on_type}'pilot_total_hours="{ pilot_total_hours}'midair="{ midair: }">\ '{airport}\ '\ {narrative}\ \ '\nformat(in... |
8,856 | example of thisalthough we won' review it here because it doesn' really show anything new parsing xml with sax (simple api for xml|unlike the element tree and domwhich represent an entire xml document in memorysax parsers work incrementallywhich can potentially be both faster and less memory-hungry performance advantag... |
8,857 | file handling class incidentsaxhandler(xml sax handler contenthandler)def __init__(selfincidents)super(__init__(self __data {self __text "self __incidents incidents self __incidents clear(custom sax handler classes must inherit the appropriate base class this ensures that for any methods we don' reimplement (because we... |
8,858 | which we ignore we always clear the self __text string when we get start tag because no text tags are nested in the aircraft incident xml file format we don' do any exception-handling in the incidentsaxhandler class if an exception occurs it will be passed up to the callerin this case the import_xml_sax(methodwhich wil... |
8,859 | file handling random access binary files ||in the earlier sections we worked on the basis that all of program' data was read into memory in one goprocessedand then all written out in one go modern computers have so much ram that this is perfectly viable approacheven for large data sets howeverin some situations holding... |
8,860 | table file object attributes and methods # syntax description close(closes file object and sets attribute closed to true closed returns true if the file is closed encoding the encoding used for bytes str conversions fileno(returns the underlying file' file descriptor (available only for file objects that have file desc... |
8,861 | file handling table file object attributes and methods # syntax description seekable(returns true if supports random access tell( truncatesizereturns the current file pointer position relative to the start of the file truncates the file to the current file pointer positionor to the given size if size is specified writa... |
8,862 | mode " +bif not os path exists(filenameelse " +bself __fh open(filenamemodeself auto_flush auto_flush there are two different record sizes the binaryrecordfile record_size is the one set by the user and is the record size from the user' point of view the private binaryrecordfile __record_size is the real record size an... |
8,863 | file handling if the arguments are okaywe move the file position pointer to the first byte of the record--notice that here we use the real record sizethat iswe account for the state byte the seek(method moves the file pointer to an absolute byte position by default second argument can be given to make the movement rela... |
8,864 | this is private supporting method used by some of the other methods to move the file position pointer to the first byte of the record at the given index position we begin by checking to see whether the given index is in range we do this by seeking to the end of the file (byte offset of from the end)and using the tell(m... |
8,865 | file handling end self __fh tell(return end /self __record_size this method reports how many records are in the binary record file it does this by dividing the end byte position ( how many bytes are in the fileby the size of record we have now covered all the basic functionality offered by the binaryrecordfile binaryre... |
8,866 | if state !_okayself __fh truncate( elselimit none for index in range(len(self - )self __seek_to_index(indexstate self __fh read( if state !_okaylimit index elsebreak if limit is not noneself __fh truncate(limit self __record_sizeself __fh flush(if the first record is blank or deletedthen they must all be blank or delet... |
8,867 | file handling if not keep_backupos remove(backupfileself __fh open(self __fh name" + "this method creates two filesa compacted file and backup copy of the original file the compacted file starts out with the same name as the original but with $$tacked on to the end of the filenameand similarly the backup file has the o... |
8,868 | if not bicycles increase_stock(bike identity )print("stock movement failed for"bike identitythis snippet opens bike stock file and iterates over all the bicycle records it contains to find the total value (sum of price quantityof the bikes held it then increases the number of "gekkobikes in stock by two and increments ... |
8,869 | file handling bike _bike_from_record(recordself __index_from_identity[bike identityindex the bikestock bikestock class is custom collection class that aggregates binary record file (self __fileand dictionary (self __index_from_identitywhose keys are bike ids and whose values are record index positions once the file has... |
8,870 | increase_stock (lambda selfidentityamountself __change_stock(identityamount)decrease_stock (lambda selfidentityamountself __change_stock(identity-amount)the private __change_stock(method provides an implementation for the increase_stock(and decrease_stock(methods the bike' index position is found and the raw binary rec... |
8,871 | file handling return bike(*partsdef _record_from_bike(bike)return _bike_struct pack(bike identity encode("utf ")bike name encode("utf ")bike quantitybike pricesequence unpacking when we convert binary record into bikestock bike we first convert the tuple returned by unpack(into list this allows us to modify elementsin ... |
8,872 | in the final section we saw how to create generic class to handle random access binary files that hold records of fixed sizeand then how to use the generic class in specific context this brings us to the end of all the fundamentals of python programming it is possible to stop reading right here and to write perfectly g... |
8,873 | file handling class this involves changing only handful of lines solution is provided in bikestock_ans py debugging binary formats can be difficultbut tool that can help is one that can do hex dump of binary file' contents create program that has the following console help textusagexdump py [optionsfile [file filen]opt... |
8,874 | further procedural programming further object-oriented programming functional-style programming advanced programming techniques |||in this we will look at wide variety of different programming techniques and introduce many additionaloften more advancedpython syntaxes some of the material in this is quite challengingbut... |
8,875 | advanced programming techniques and operator modules this section also shows how to use partial function application to simplify codeand how to create and use coroutines all the previous put together have provided us with the "standard python toolboxthis takes everything that we have already covered and turns it into t... |
8,876 | elif action =" "list_dvds(dbelif action =" "remove_dvd(dbelif action =" "import_(dbelif action =" "export(dbelif action =" "quit(db functions dict( =add_dvde=edit_dvdl=list_dvdsr=remove_dvdi=import_x=exportq=quitfunctions[action](dbthe choice is held as one-character string in the action variableand the database to be ... |
8,877 | advanced programming techniques identical to list comprehensionsthe difference being that they are enclosed in parentheses rather than brackets here are their syntaxes(expression for item in iterable(expression for item in iterable if conditionin the preceding we created some iterator methods using yield expressions he... |
8,878 | received (yield next_quarterif received is nonenext_quarter + elsenext_quarter received the yield expression returns each value to the caller in turn in additionif the caller calls the generator' send(methodthe value sent is received in the generator function as the result of the yield expression here is how we can use... |
8,879 | advanced programming techniques in either case the function is expected to be called with list of filenamesfor examplesys argv[ :]as its argument on windows the function iterates over all the names listed for each filenamethe function yields the namebut for nonfiles (usually directories)the glob module' glob iglob(func... |
8,880 | this is fine for user-entered expressionsbut what if we need to create function dynamicallyfor that we can use the built-in exec(function for examplethe user might give us formula such as and the name "area of sphere"which they want turned into function assuming that we replace with math pithe function they want can be... |
8,881 | advanced programming techniques after the exec(call the context dictionary contains key called "area_of_ spherewhose value is the area_of_sphere(function here is how we can access and call the functionarea_of_sphere context["area_of_sphere"area area_of_sphere( area = the area_of_sphere object is an object reference to ... |
8,882 | get_file_type get_function(module"get_file_type"if get_file_type is not noneget_file_type_functions append(get_file_typein momentwe will look at three different implementations of the load_modules(function which returns (possibly emptylist of module objectsand we will look at the get_function(function further on for ea... |
8,883 | advanced programming techniques fh none tryfh open(filename" "encoding="utf "code fh read(module type(sys)(namesys modules[namemodule exec(codemodule __dict__modules append(moduleexcept (environmenterrorsyntaxerroras errsys modules pop(namenoneprint(errfinallyif fh is not nonefh close(return modules we begin by iterati... |
8,884 | table dynamic programming and introspection functions syntax description __import__imports module by namesee text compile(sourcefilemodereturns the code object that results from compiling the source textfile should be the filenameor ""mode must be "single""eval"or "execdelattr(objnamedeletes the attribute called name f... |
8,885 | advanced programming techniques one theoretical problem with this approach is that it is potentially insecure the name variable could begin with sysand be followed by some destructive code and here is the third approachagain just showing the replacement for the first approach' try except blocktrymodule __import__(namem... |
8,886 | advanced programming techniques one common use case for local functions is when we want to use recursion in these casesthe enclosing function is calledsets things upand then makes the first call to local recursive function recursive functions (or methodsare ones that call themselves structurallyall directly recursive f... |
8,887 | before ["nonmetals"hydrogen"carbon"nitrogen"oxygen""inner transitionals"lanthanides"cerium"europium"actinides"uranium"curium"plutonium""alkali metals"lithium"sodium"potassium" after ["alkali metals"lithium"potassium"sodium""inner transitionals"actinides"curium"plutonium"uranium"lanthanides"cerium"europium""nonmetals"ca... |
8,888 | advanced programming techniques the code begins by creating three constants that are used to provide names for index positions used by the local functions then we define the two local functions which we will review in moment the sorting algorithm works in two stages in the first stage we create list of entrieseach -tup... |
8,889 | [('nonmetals''nonmetals'[('hydrogen'hydrogen'[])('carbon'carbon'[])('nitrogen'nitrogen'[])('oxygen'oxygen'[])])('inner transitionals''inner transitionals'[('lanthanides'lanthanides'[('cerium'cerium'[])('europium'europium'[])])('actinides'actinides'[('uranium'uranium'[])('curium'curium'[])('plutonium'plutonium'[])])])('... |
8,890 | advanced programming techniques need to change level' valueand just as we need to tell python that we want to change global variables using the global statement (to prevent new local variable from being created rather than the global variable updated)the same applies to variables that we want to change but which belong... |
8,891 | for our first decorator examplelet us suppose that we have many functions that perform calculationsand that some of these must always produce positive result we could add an assertion to each of thesebut using decorator is easier and clearer here' function decorated with the @positive_result decorator that we will crea... |
8,892 | advanced programming techniques in some cases it would be useful to be able to parameterize decoratorbut at first sight this does not seem possible since decorator takes just one argumenta function or method but there is neat solution to this we can call function with the parameters we want and that returns decorator w... |
8,893 | if python is run in debug mode (the normal mode)every time the discounted_price(function is called log message will be added to the file logged log in the machine' local temporary directoryas this log file extract illustratescalleddiscounted_price( - calleddiscounted_price( - calleddiscounted_price( make_integer=true- ... |
8,894 | advanced programming techniques in debug mode the global variable __debug__ is true if this is the case we set up logging using the logging moduleand then create the @logged decorator the logging module is very powerful and flexible--it can log to filesrotated filesemailsnetwork connectionshttp serversand more here we'... |
8,895 | def is_unicode_punctuation( str-boolfor in sif unicodedata category( )[ !" "return false return true every unicode character belongs to particular category and each category is identified by two-character identifier all the categories that begin with are punctuation characters here we have used python data types as the... |
8,896 | advanced programming techniques this decorator requires that every argument and the return value must be annotated with the expected type it checks that the function' arguments and return type are all annotated with their types when the function it is passed is createdand at runtime it checks that the types of the actu... |
8,897 | annotations are very new feature of pythonand because python does not impose any predefined meaning on themthe uses they can be put to are limited only by our imagination further ideas for possible usesand some useful linksare available from pep "function annotations"www python orgdev/peps/pep- further object-oriented ... |
8,898 | advanced programming techniques class orddef __getattr__(selfchar)return ord(charwith the ord class availablewe can create an instanceord ord()and then have an alternative to the built-in ord(function that works for any character that is valid identifier for exampleord returns ord returns and ord returns (but ord and s... |
8,899 | table attribute access special methods special method usage __delattr__(selfnamedel deletes object ' attribute __dir__(selfdir(x__getattr__(selfname__getattribute__(selfnamedescription returns list of ' attribute names returns the value of object ' attribute if it isn' found directly returns the value of object ' attri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.