1. 首页
  2. 编程语言
  3. Python
  4. PythonStandardLibrary

PythonStandardLibrary

上传者: 2019-05-02 09:01:34上传 PDF文件 794.31KB 热度 23次
Python Standard Library is an essential guide for serious Python programmers. Python is a modular language that imports most useful operations from the standard library (basic support modules; operating system interfaces; network protocols; file formats; data conversions; threads and processes; and Python Standard Library Core ModulesCore modulesSince the functions in the C runtime library are not part of the Win32API, we believe the number of applications that will be affected by thisbug to be very limitedMicrosoft, January 1999OverviewPythons standard library covers a wide range of modules. Everything from modules that are as much apart of the Python language as the types and statements defined by the language specification, toobscure modules that are probably useful only to a small number of programs.This section describes a number of fundamental standard library modules. Any larger Python programis likely to use most of these modules, either directly or indirectlyBuilt-in Functions and ExceptionsTwo modules are even more basic than all other modules combined: the builtin module definesbuilt-in functions (like len, int, and range), and the exceptions module defines all built-inoptions.Python imports both modules when it starts up, and makes their content available for all programsOperating System Interface ModulesThere are a number of modules providing platform-independent interfaces to the underlying operatingsystem. They are modeled after the PoSiX standard aPi and the standard c library.The modules in this group include os, which provides file and process operations, os path whichoffers a platform-independent way to pull apart and put together file names and time which providesfunctions to work with dates and timesTo some extent, networking and thread support modules could also belong in this group, but they arenot supported by all Python implementationsPython Standard libraryCopyright(c)1999-2003 by Fredrik Lundh. All rights reserved.Python Standard Library Core ModulesType Support ModulesSeveral built-in types have support modules in the standard library. The string module implementscommonly used string operations, the math module provides math operations and constants, and thecmath module does the same for complex numbersRegular ExpressionsThe re module provides regular expressions support for Python. Regular expressions are stringpatterns written in a special syntax, which can be used to match strings, and extract substringsanguage Support modulessys gives you access to various interpreter variables, such as the module search path, and theinterpreter version. operator provides functional equivalents to many built-in operators. copy allowsyou to copy objects. And finally, gc gives you more control over the garbage collector facilities inthon 2.0Python Standard Library Core Modules1-3The builtin moduleThis module contains built-in functions which are automatically available in all Python modules. youusually don ' t have to import this module, python does that for you when necessaryCalling a function with arguments from a tuple or dictionaryPython allows you to build function argument lists on the fly. Just put all the arguments in a tuple, andcall the built-in apply functionExample: Using the apply functionFile: builtin-apply-example-1 pydef function a, b)print a, bapply function,("whither,canada? )apply(function,(1, 2+3))Whither canada?15To pass keyword arguments to a function, you can use a dictionary as the third argument to applyExample: Using the apply function to pass keyword argumentsFile: builtin-apply-example-2 pydef function (a, b)print a, bapply(function, "crunchy ,"frog))apply(function, ("crunchy",[b:frog"])apply (function o,i a: crunchy, b: frog )crunchy frogcrunchy frogcrunchy frogPython Standard Library Core ModulesOne common use for apply is to pass constructor arguments from a subclass on to the base class,especially if the constructor takes a lot of argumentsExample: Using the apply function to call base class constructorsFile: builtin-apply-example-3pyclass rectangledef_ init(self, color="white, width=10, height=10)print "create a color, self, sized",width,x", heightclass rounded Rectangle(rectangle)def init(self, **kwapply (rectangle.__init(self,), kw)rect Rectangle(color=green", height=100, width=100)rect=RoundedRectangle(color="blue, height=20)create a green sized 100 X 100create a blue Roundedrectangle instance at 8c84c0> sized 10 X 20Python 2.0 provides an alternate syntax. Instead of apply, you can use an ordinary function call, anduse*to mark the tuple, and **to mark the dictionary.The following two statements are equivalent:result function *args, x*kwargs)result= apply (function args, kwargsLoading and reloading modulesIf you've written a Python program larger than just a few lines, you know that the import statement isused to import external modules (you can also use the from-import version). What you might noknow already is that import delegates the actual work to a built-in function called_ importPython Standard Library Core ModulesThe trick is that you can actually call this function directly. This can be handy if you have the modulename in a string variable, like in the following example, which imports all modules whose names endwith"-pluginExample: Using the_import function to load named modulesFile: builtin-import-example-1 pymport glob,OSmodules =[for module_file in globglob "*-plugin. pytmodule_name, ext os path. splitext(os path basename (module_ _ file))moduleimport (module namemodules. append (module)except ImportError:pass ignore broken modulessay hello to all modulesfor module in modules:module hellooexample-plugin says helloNote that the plugin modules have hyphens in the name. This means that you cannot import such amodule using the ordinary import command, since you cannot have hyphens in Python identifiersHere's the plugin used in this exampleExample: A sample pluginFile: example-plugin pydef hellooprint example-plugin says hello"The following example shows how to get a function object, given that you have the module andfunction name as stringsExample: Using the import function to get a named functionFile: builtin-import-example-2pydef getfunctionbyname(module_name, function_ name):module=_import(module_namereturn getattr(module, function_name)print repr(getfunctionbyname( dumbdbm"open"))Python Standard Library Core ModulesYou can also use this function to implement lazy loading of modules. In the following example, thestring module is imported when it is first usedExample: Using the_ import function to implement lazy importFile: builtin-import-example-3pyclass lazyimportdef init (self, module_name)self. module name module nameself, module Nonedef_ (self, name)if self. module is none.self module =_import_(self module_name)return getattr(self. module, name)string LazyImport( string")print string. lowercaseabcdefghijklmnopqrstuvwxyzPython provides some basic support for reloading modules that you' ve already imported. The followingexample loads the hello. py file three timesExample: Using the reload function#f File: builtin-reload-example-1 pyimport helloreload (helloreload (hellohello again and welcome to the showhello again and welcome to the showhello again and welcome to the showreload uses the module name associated with the module object not the variable name. This meansthat even if you, ve renamed the module, reload will still be able to find the original moduleNote that when you reload a module, it is recompiled and the new module replaces the old one in themodule dictionary. However if you have created instances of classes defined in that module, thoseinstances will still use the old implementatioLikewise, if you' ve used from-import to create references to module members in other modulesthose references will not be updatedPython Standard Library Core ModulesLooking in namespacesThe dir function returns a list of all members of a given module, class, instance, or other type. It'sprobably most useful when you're working with an interactive Python interpreter, but can also come inhandy in other situationsExample: Using the dir functionFile: builtin-dir-example-1 pydef dumplvalue)print value, => dir(value)Import sysdump(o)dump(1.0dump(o0j# complex numberdump([d# listdump(i)# dictionarydump( stringdump(len ) functiondump(sys)# module1.0=>[]0j=>[conjugate, imag,'real][]=>[append,'count,'extend,'index', insert,pop,remove, 'reverse, sort=>[clear,'copy, 'get, ' has key, items,keys,update, 'values'string ==>[ docnamesef”]=>[docnamestderrstdinstdoutargvbuiltin module names,copyright,'dllhandleexc_info,,'exc_type, 'exec_prefix''executableIn the following example, the getmember function returns all class-level attributes and methodsdefined by a given classExample: Using the dir function to find all members of a classFile: builtin-dir-example-2pyclass a:def a self)passdef b self:passPython Standard Library Core Modules8class B(a)def c(self)passdef d(self)passdef getmembers(klass, members=None):#f get a list of all class members, ordered by classif members is nonemembers=[for k in klass, basesgetmembers(k, members)for m in dir(klass)if m not in membersmembers. append (m)return membersprint getmembers(a)print getmembers(B)print getmembers(ioError)docdulea',"b[ docmodule',"a',"b','c',"d"]docgetitemodulestrNote that the getmembers function returns an ordered list. The earlier a name appears in the list, thehigher up in the class hierarchy it' s defined if order doesn t matter, you can use a dictionary to collectthe names instead of a listThe vars function is similar, but it returns a dictionary containing the current value for each memberyou use it without an argument, it returns a dictionary containing what's visible in the current localnamespaceExample: using the vars functionFile: builtin-vars-example-1 pybook= library2pages =250scripts 350print the %(book)s book contains more than %(scripts )s scripts"% varsothe library book contains more than 350 scripts
下载地址
用户评论
码姐姐匿名网友 2019-05-02 09:01:34

不错不错不错