• Aucun résultat trouvé

Common Duck-Typing Protocols

Dans le document Pro Django (Page 35-38)

?kjp]_pejbkni]pekjlnkre`a`sdajoaj`ejciaoo]caopkpdaksjankbpdaoepa*

j]ia9ik`aho*?d]nBeah`$i]t[hajcpd9.11%

ai]eh9ik`aho*Ai]ehBeah`$%

This simple code alone is enough to allow the framework to imbue the new class with a wealth of additional functionality, without requiring the programmer to deal with that process manually. Also note how all the attribute classes are provided from that same base module and are instantiated when assigned to the model.

A class declaration is never limited to only those features provided by the framework.

Since any valid Python code is allowed, your classes may contain a variety of methods and other attributes, intermingled with a framework’s provided features.

Common Duck-Typing Protocols

You’ve probably heard the old adage, “If it walks like a duck, and talks like a duck, it’s a duck.”

Shakespeare played on this idea a bit more romantically when he wrote in Romeo and Juliet,

“that which we call a rose by any other name would smell as sweet.” The recurring theme here is that the name given to an object has no bearing on its true nature. The idea is that, regardless of labels, you can be reasonably sure what something is just by looking at its behavior.

In Python, and in some other languages, this concept is extended to refer to object types.

Rather than relying on some base class or interface to define what an object can do, it simply implements the attributes and methods necessary to behave as expected. A common example of this in Python is a “file- like object,” which is any object that implements at least some of the same methods as a Python file object. In this way, many libraries may return their own objects that can be passed to other functions that expect a file object while retaining special abilities, such as being read- only, compressed, encrypted, pulled from an Internet- connected source or any number of other possibilities.

Also, like interfaces in other languages, Python objects can be more than one type of duck at a time. It’s not uncommon, for instance, to have an object that can behave as a dictionary in some respects, while behaving like a list in others. Django’s DpplNaolkjoa object exhibits both of these behaviors, as well as mimicking an open file object.

In Django, many features utilize duck-typing by not providing a particular base class.

Instead, each feature defines a protocol of sorts, a set of methods and attributes that an object must provide in order to function properly. Many of these protocols are presented in the offi-cial Django documentation and this book will cover many more. You will also see some of the special abilities that can be provided by using this technique.

The following sections describe a few common Python protocols that you’ll see through-out Django, and indeed throughthrough-out any large Python library.

Callables

Python allows code to be executed from a number of sources, and anything that can be exe-cuted in the same manner as a typical function is designated as callable. All functions, classes and methods are automatically callable, as would be expected, but instances of arbitrary object classes can be designated as callable as well, by providing a single method.

__call__(self[, ...])

This method will be executed when the instantiated object is called as a function. It works just like any other member function, differing only in the manner in which it’s called.

:::_h]ooIqhpelhean$k^fa_p%6

***`ab[[ejep[[$oahb(b]_pkn%6

***oahb*b]_pkn9b]_pkn

***`ab[[_]hh[[$oahb(r]hqa%6

***napqnjr]hqa&oahb*b]_pkn

***

:::peiao.9Iqhpelhean$.%

:::peiao.$1%

-,

:::peiao.$-,%

.,

:::peiao/9Iqhpelhean$/%

:::peiao/$-,%

/,

Python also provides a built- in function to assist in the identification of callable objects.

The _]hh]^ha$% function takes a single argument, returning Pnqa or B]hoa, indicating whether the object can be called as a function.

:::_h]oo>]oe_$k^fa_p%6

***l]oo

***

:::_h]oo?]hh]^ha$k^fa_p%6

***`ab[[_]hh[[$oahb%6

***napqnjAta_qpa`

***

:::^9>]oe_$%

:::_]hh]^ha$^%

B]hoa

:::_9?]hh]^ha$%

:::_]hh]^ha$_%

Pnqa

Dictionaries

A dictionary is a mapping between keys and values within a single object. Most programming languages have dictionaries in some form; other languages call them “hashes,” “maps” or

“associative arrays.” In addition to simple access to values by specifying a key, dictionaries in Python provide a number of methods for more fine- grained manipulation of the underlying mapping. To behave even more like a true dictionary, an object may provide other methods, documented in the Python Library Reference.3

__contains__(self, key)

Used by the ej operator, this returns Pnqa if the specified key is present in the underlying map-ping, and returns B]hoa otherwise. This should never raise an exception.

__getitem__(self, key)

This returns the value referenced by the specified key, if it exists. If the key is not present in the underlying mapping, it should raise a GauAnnkn.

__setitem__(self, key, value)

This stores the specified value to be referenced later by the specified key. This should overwrite any existing value referenced by the same key, if such a mapping is already present.

:::_h]oo?]oaEjoajoepera@e_p$`e_p%6

***`ab[[ejep[[$oahb(&&gs]nco%6

***bkngau(r]hqaejgs]nco*epaio$%6

***oahbWgau*hksan$%Y9r]hqa

***`ab[[_kjp]ejo[[$oahb(gau%6

***napqnjoqlan$?]oaEjoajoepera@e_p(oahb%*[[_kjp]ejo[[$gau*hksan$%%

***`ab[[capepai[[$oahb(gau%6

***napqnjoqlan$?]oaEjoajoepera@e_p(oahb%*[[capepai[[$gau*hksan$%%

***`ab[[oapepai[[$oahb(gau(r]hqa%6

***oqlan$?]oaEjoajoepera@e_p(oahb%*[[oapepai[[$gau*hksan$%(r]hqa%

***

:::`9?]oaEjoajoepera@e_p$Ol=i9#acco#%

:::#ol]i#ej`

Pnqa

:::`W#OL=I#Y

#acco#

:::`W#oL]I#Y9#^qncan#

:::`W#Ol]I#Y

#^qncan#

Dictionaries are also expected to be iterable, with the list of keys used when code loops over a dictionary’s contents. Refer to the upcoming “Iterables” section for more information.

3. dppl6++lnk`f]jck*_ki+`e_p)iapdk`o+

Files

As mentioned previously, files are a common way to access information, and many Python libraries provide file- like objects for use with other file- related functions. A file- like object doesn’t need to supply all of the following methods, just those that are necessary to func-tion properly. In the case of the file protocol, objects are free to implement read access, write access or both. Not all methods are listed here, but only the most common. A full list of file methods is available in the Python standard library documentation, so be sure to check there for more details.4

read(self, [size])

This retrieves data from the object or its source of information. The optional oeva argument contains the number of bytes to be retrieved; if omitted, the method should return as many bytes as possible (often the entire file, if available, or perhaps all the bytes available on a net-work interface).

write(self, str)

This writes the specified opn to the object or its source of information.

close(self)

This closes the file so it can no longer be accessed. This can be used to free any memory resources that had been allocated, to commit the object’s contents to disk or simply to satisfy the protocol. Even if this method provides no special functionality, it should be provided to avoid unnecessary errors.

Dans le document Pro Django (Page 35-38)