[ Pobierz całość w formacie PDF ]
.Note that the returned list contains the namesof the methods as strings, not the methods themselves.d is a dictionary, so dir(d) returns a list of the names of dictionary methods.At least one of these, keys,should look familiar.This is where it really gets interesting.odbchelper is a module, so dir(odbchelper) returns a list of allkinds of stuff defined in the module, including built-in attributes, like __name__, __doc__, and whateverother attributes and methods you define.In this case, odbchelper has only one user-defined method, thebuildConnectionString function described in Chapter 2.Finally, the callable function takes any object and returns True if the object can be called, or False otherwise.Dive Into Python 34 Callable objects include functions, class methods, even classes themselves.(More on classes in the next chapter.)Example 4.8.Introducing callable>>> import string>>> string.punctuation'!"#$%&\'()*+,-./:;?@[\\]^_`{|}~'>>> string.join>>> callable(string.punctuation)False>>> callable(string.join)True>>> print string.join.__doc__join(list [,sep]) -> stringReturn a string composed of the words in list, withintervening occurrences of sep.The default separator is asingle space.(joinfields and join are synonymous)The functions in the string module are deprecated (although many people still use the joinfunction), but the module contains a lot of useful constants like this string.punctuation,which contains all the standard punctuation characters.string.join is a function that joins a list of strings.string.punctuation is not callable; it is a string.(A string does have callable methods, butthe string itself is not callable.)string.join is callable; it's a function that takes two arguments.Any callable object may have a doc string.By using the callable function on each of anobject's attributes, you can determine which attributes you care about (methods, functions, classes)and which you want to ignore (constants and so on) without knowing anything about the objectahead of time.4.3.3.Built-In Functionstype, str, dir, and all the rest of Python's built-in functions are grouped into a special module called__builtin__.(That's two underscores before and after.) If it helps, you can think of Python automaticallyexecuting from __builtin__ import * on startup, which imports all the "built-in" functions into thenamespace so you can use them directly.The advantage of thinking like this is that you can access all the built-in functions and attributes as a group by gettinginformation about the __builtin__ module.And guess what, Python has a function called info.Try it yourselfand skim through the list now.We'll dive into some of the more important functions later.(Some of the built-in errorclasses, like AttributeError, should already look familiar.)Example 4.9.Built-in Attributes and Functions>>> from apihelper import info>>> import __builtin__>>> info(__builtin__, 20)ArithmeticError Base class for arithmetic errors.AssertionError Assertion failed.AttributeError Attribute not found.Dive Into Python 35 EOFError Read beyond end of file.EnvironmentError Base class for I/O related errors.Exception Common base class for all exceptions.FloatingPointError Floating point operation failed.IOError I/O operation failed.[.snip.]Python comes with excellent reference manuals, which you should peruse thoroughly to learn all the modules Pythonhas to offer.But unlike most languages, where you would find yourself referring back to the manuals or man pagesto remind yourself how to use these modules, Python is largely self-documenting.Further Reading on Built-In Functions" Python Library Reference (http://www.python.org/doc/current/lib/) documents all the built-in functions(http://www.python.org/doc/current/lib/built-in-funcs.html) and all the built-in exceptions(http://www.python.org/doc/current/lib/module-exceptions.html).4.4.Getting Object References With getattrYou already know that Python functions are objects.What you don't know is that you can get a reference to a functionwithout knowing its name until run-time, by using the getattr function.Example 4.10.Introducing getattr>>> li = ["Larry", "Curly"]>>> li.pop>>> getattr(li, "pop")>>> getattr(li, "append")("Moe")>>> li["Larry", "Curly", "Moe"]>>> getattr({}, "clear")>>> getattr((), "pop")Traceback (innermost last):File "", line 1, in ?AttributeError: 'tuple' object has no attribute 'pop'This gets a reference to the pop method of the list.Note that this is not calling the pop method; that would beli.pop().This is the method itself.This also returns a reference to the pop method, but this time, the method name is specified as a stringargument to the getattr function.getattr is an incredibly useful built-in function that returns anyattribute of any object.In this case, the object is a list, and the attribute is the pop method.In case it hasn't sunk in just how incredibly useful this is, try this: the return value of getattr is the method,which you can then call just as if you had said li.append("Moe") directly.But you didn't call the functiondirectly; you specified the function name as a string instead.getattr also works on dictionaries.In theory, getattr would work on tuples, except that tuples have no methods, so getattr will raise anexception no matter what attribute name you give.Dive Into Python 36 4.4.1.getattr with Modulesgetattr isn't just for built-in datatypes.It also works on modules.Example 4.11.The getattr Function in apihelper.py>>> import odbchelper>>> odbchelper.buildConnectionString>>> getattr(odbchelper, "buildConnectionString")>>> object = odbchelper>>> method = "buildConnectionString">>> getattr(object, method)>>> type(getattr(object, method))>>> import types>>> type(getattr(object, method)) == types.FunctionTypeTrue>>> callable(getattr(object, method))TrueThis returns a reference to the buildConnectionString function in the odbchelper module, whichyou studied in Chapter 2, Your First Python Program.(The hex address you see is specific to my machine; youroutput will be different.)Using getattr, you can get the same reference to the same function.In general, getattr(object,"attribute") is equivalent to object.attribute.Ifobject is a module, thenattribute can beanything defined in the module: a function, class, or global variable.And this is what you actually use in the info function.object is passed into the function as an argument;method is a string which is the name of a method or function.In this case, method is the name of a function, which you can prove by getting its type.Since method is a function, it is callable.4.4.2.getattr As a DispatcherA common usage pattern of getattr is as a dispatcher.For example, if you had a program that could output data ina variety of different formats, you could define separate functions for each output format and use a single dispatchfunction to call the right one [ Pobierz całość w formacie PDF ]

  • zanotowane.pl
  • doc.pisz.pl
  • pdf.pisz.pl
  • ines.xlx.pl