Quiz Flashcards
(185 cards)
How can you determine how large a tuple is? Why is this tool located where it is?
The built-in len function returns the length (number of contained items) for any container object in Python, including tuples. It is a built-in function instead of a type method because it applies to many different types of objects. In general, built- in functions and expressions may span many object types; methods are specific to a single object type, though some may be available on more than one type (index, for example, works on lists and tuples).
Writeanexpressionthatchangesthefirstiteminatuple.(4, 5, 6)shouldbecome (1, 5, 6) in the process.
Because they are immutable, you canÕt really change tuples in place, but you can generate a new tuple with the desired value. Given T = (4, 5, 6), you can change the first item by making a new tuple from its parts by slicing and concatenating: T = (1,) + T[1:].(Recallthatsingle-itemtuplesrequireatrailingcomma.)Youcould also convert the tuple to a list, change it in place, and convert it back to a tuple, but this is more expensive and is rarely required in practiceÑsimply use a list if you know that the object will require in-place changes.
What is the default for the processing mode argument in a file open call?
The default for the processing mode argument in a file open call is ‘r’, for reading text input. For input text files, simply pass in the external fileÕs name.
What module might you use to store Python objects in a file without converting them to strings yourself?
The pickle module can be used to store Python objects in a file without explicitly converting them to strings. The struct module is related, but it assumes the data is to be in packed binary format in the file; json similarly converts a limited set of Python objects to and from strings per the JSON format.
How might you go about copying all parts of a nested structure at once?
Import the copy module, and call copy.deepcopy(X) if you need to copy all parts of a nested structure X. This is also rarely seen in practice; references are usually the desired behavior, and shallow copies (e.g., aList[:], aDict.copy(), set(aSet)) usually suffice for most copies.
When does Python consider an object true?
An object is considered true if it is either a nonzero number or a nonempty collec- tion object. The built-in words True and False are essentially predefined to have the same meanings as integer 1 and 0, respectively.
What is your quest?
Acceptable answers include ÒTo learn Python,Ó ÒTo move on to the next part of the book,Ó or ÒTo seek the Holy Grail.Ó
What conclusions can you draw from this chapter about the relative speed of Python iteration tools?
In general, list comprehensions are usually the quickest of the bunch; map beats list comprehensions in Python only when all tools must call functions; for loops tend to be slower than comprehensions; and generator functions and expressions are slower than comprehensions by a constant factor. Under PyPy, some of these find- ings differ; map often turns in a different relative performance, for example, and list comprehensions seem always quickest, perhaps due to function-level optimiza- tions. At least thatÕs the case today on the Python versions tested, on the test machine used, and for the type of code timedÑthese results may vary if any of these three variables differ. Use the homegrown timer or standard library timeit to test your use cases for more relevant results. Also keep in mind that iteration is just one component of a programÕs time: more code gives a more complete picture.
What conclusions can you draw from this chapter about the relative speed of the Pythons timed?
In general, PyPy 1.9 (implementing Python 2.7) is typically faster than CPython 2.7, and CPython 2.7 is often faster than CPython 3.3. In most cases timed, PyPy is some 10X faster than CPython, and CPython 2.7 is often a small constant faster than CPython 3.3. In cases that use integer math, CPython 2.7 can be 10X faster than CPython 3.3, and PyPy can be 100X faster than 3.3. In other cases (e.g., string operations and file iterators), PyPy can be slower than CPython by 10X, though timeit and memory management differences may influence some results. The pystone benchmark confirms these relative rankings, though the sizes of the dif- ferences it reports differ due to the code timed. At least thatÕs the case today on the Python versions tested, on the test machine used, and for the type of code timedÑthese results may vary if any of these three variables differ. Use the homegrown timer or standard library timeit to test your use cases for more relevant results. This is especially true when timing Python implementations, which may be arbitrarily optimized in each new release.
What is the point of coding functions?
Functions are the most basic way of avoiding code redundancy in PythonÑfactor- ing code into functions means that we have only one copy of an operationÕs code to update in the future. Functions are also the basic unit of code reuse in Python Ñwrapping code in functions makes it a reusable tool, callable in a variety of pro- grams. Finally, functions allow us to divide a complex system into manageable parts, each of which may be developed individually.
At what time does Python create a function?
A function is created when Python reaches and runs the def statement; this state- ment creates a function object and assigns it the functionÕs name. This normally happens when the enclosing module file is imported by another module (recall that imports run the code in a file from top to bottom, including any defs), but it can also occur when a def is typed interactively or nested in other statements, such as ifs.
What does a function return if it has no return statement in it?
A function returns the None object by default if the control flow falls off the end of the function body without running into a return statement. Such functions are usually called with expression statements, as assigning their None results to vari- ables is generally pointless. A return statement with no expression in it also returns None.
When does the code nested inside the function definition statement run?
The function body (the code nested inside the function definition statement) is run when the function is later called with a call expression. The body runs anew each time the function is called.
WhatÕs wrong with checking the types of objects passed into a function?
Checking the types of objects passed into a function effectively breaks the func- tionÕs flexibility, constraining the function to work on specific types only. Without such checks, the function would likely be able to process an entire range of object typesÑany objects that support the interface expected by the function will work. (The term interface means the set of methods and expression operators the func- tionÕs code runs.)
What is a metaclass?
A metaclass is a class used to create a class. Normal new-style classes are instances of the type class by default. Metaclasses are usually subclasses of the type class, which redefines class creation protocol methods in order to customize the class creation call issued at the end of a class statement; they typically redefine the methods __new__ and __init__ to tap into the class creation protocol. Metaclasses can also be coded other waysÑas simple functions, for exampleÑbut they are always responsible for making and returning an object for the new class. Meta- classes may have methods and data to provide behavior for their classes tooÑand constitute a secondary pathway for inheritance searchÑbut their attributes are accessible only to their class instances, not to their instanceÕs instances.
How do you declare the metaclass of a class?
In Python 3.X, use a keyword argument in the class header line: class C(meta class=M). In Python 2.X, use a class attribute instead: __metaclass__ = M. In 3.X, the class header line can also name normal superclasses before the metaclass key- word argument; in 2.X you generally should derive from object too, though this is sometimes optional.
How do class decorators overlap with metaclasses for managing classes?
Because both are automatically triggered at the end of a class statement, class decorators and metaclasses can both be used to manage classes. Decorators rebind a class name to a callableÕs result and metaclasses route class creation through a callable, but both hooks can be used for similar purposes. To manage classes, decorators simply augment and return the original class objects. Metaclasses aug- ment a class after they create it. Decorators may have a slight disadvantage in this role if a new class must be defined, because the original class has already been created.
How do class decorators overlap with metaclasses for managing instances?
Because both are automatically triggered at the end of a class statement, we can use both class decorators and metaclasses to manage class instances, by inserting a wrapper (proxy) object to catch instance creation calls. Decorators may rebind the class name to a callable run on instance creation that retains the original class object. Metaclasses can do the same, but may have a slight disadvantage in this role, because they must also create the class object.
Would you rather count decorators or metaclasses amongst your weaponry? (And please phrase your answer in terms of a popular Monty Python skit.)
Our chief weapon is decorators…decorators and metaclasses…metaclasses and decorators… Our two weapons are metaclasses and decorators…and ruthless effi- ciency… Our three weapons are metaclasses, decorators, and ruthless effi- ciency…and an almost fanatical devotion to Python… Our four…no… Amongst our weapons… Amongst our weaponry…are such elements as metaclasses, decora- tors… IÕll come in again…
What is multiple inheritance?
Multiple inheritance occurs when a class inherits from more than one superclass; itÕs useful for mixing together multiple packages of class-based code. The left-to- right order in class statement headers determines the general order of attribute searches.
What is delegation?
Delegationinvolveswrappinganobjectinaproxyclass,whichaddsextrabehavior and passes other operations to the wrapped object. The proxy retains the interface of the wrapped object.
What is composition?
Composition is a technique whereby a controller class embeds and directs a num- ber of objects, and provides an interface all its own; itÕs a way to build up larger structures with classes.
What are bound methods?
Bound methods combine an instance and a method function; you can call them without passing in an instance object explicitly because the original instance is still available.
What are pseudoprivate attributes used for?
Pseudoprivate attributes (whose names begin but do not end with two leading underscores: __X) are used to localize names to the enclosing class. This includes both class attributes like methods defined inside the class, and self instance at- tributes assigned inside the classÕs methods. Such names are expanded to include the class name, which makes them generally unique.