Python论坛  - 讨论区

标题:[python-chinese] 请问什么是descriptor?是不是类有函数了就是descriptor?

2007年01月13日 星期六 23:52

Gao Hong joy.highland在gmail.com
星期六 一月 13 23:52:02 HKT 2007

ÔÚÀàÀïÃæÀÏÌáµ½Õâ¸ö£¬¿ÉÎÒ¾ÍÊÇ¿´²»Ã÷°×£¬Çë´ó¼ÒÖ¸½ÌһϰÉ

-- 
It's a long journey to go!
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070113/2e408c08/attachment.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年01月14日 星期日 00:18

yi huang yi.codeplayer在gmail.com
星期日 一月 14 00:18:52 HKT 2007

On 1/13/07, Gao Hong <joy.highland at gmail.com> wrote:
>
> 在类里面老提到这个,可我就是看不明白,请大家指教一下吧
>
> --
> It's a long journey to go!
> _______________________________________________
> python-chinese
> Post: send python-chinese at lists.python.cn
> Subscribe: send subscribe to python-chinese-request at lists.python.cn
> Unsubscribe: send unsubscribe to  python-chinese-request at lists.python.cn
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
>
 理解 python 的 method 和 function 兼谈
descriptor<http://codeplayer.blogspot.com/2006/12/python-method-function-descriptor.html>
http://users.rcn.com/python/download/Descriptor.htm

-- 
http://codeplayer.blogspot.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://python.cn/pipermail/python-chinese/attachments/20070114/91f86ce8/attachment-0001.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年01月14日 星期日 00:29

Gao Hong joy.highland在gmail.com
星期日 一月 14 00:29:59 HKT 2007

²»ºÃÒâ˼£¬ÎÒÕâÀïÉϲ»È¥£¬ÄÜ°ïÎÒתһÏÂÂð£¿

2007/1/14, yi huang <yi.codeplayer在gmail.com>:
>
> On 1/13/07, Gao Hong <joy.highland在gmail.com> wrote:
> >
> > ÔÚÀàÀïÃæÀÏÌáµ½Õâ¸ö£¬¿ÉÎÒ¾ÍÊÇ¿´²»Ã÷°×£¬Çë´ó¼ÒÖ¸½ÌһϰÉ
> >
> > --
> > It's a long journey to go!
> > _______________________________________________
> > python-chinese
> > Post: send python-chinese在lists.python.cn
> > Subscribe: send subscribe to python-chinese-request在lists.python.cn
> > Unsubscribe: send unsubscribe to
> > python-chinese-request在lists.python.cn
> > Detail Info: http://python.cn/mailman/listinfo/python-chinese
> >
> Àí½â python µÄ method ºÍ function ¼æ̸ descriptor<http://codeplayer.blogspot.com/2006/12/python-method-function-descriptor.html>
> http://users.rcn.com/python/download/Descriptor.htm
>
> --
> http://codeplayer.blogspot.com/
> _______________________________________________
> python-chinese
> Post: send python-chinese在lists.python.cn
> Subscribe: send subscribe to python-chinese-request在lists.python.cn
> Unsubscribe: send unsubscribe to  python-chinese-request在lists.python.cn
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
>



-- 
It's a long journey to go!
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070114/0d833dd3/attachment.htm 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年01月14日 星期日 00:39

头太晕 torrycn在gmail.com
星期日 一月 14 00:39:31 HKT 2007

ÔÚ07-1-14£¬Gao Hong <joy.highland在gmail.com> дµÀ£º
>
> ²»ºÃÒâ˼£¬ÎÒÕâÀïÉϲ»È¥£¬ÄÜ°ïÎÒתһÏÂÂð£¿


ÎÒ°ïÄãתһÏ°ɡ£ºÜ³¤ºÜ³¤¡£¡£¡£

How-To Guide for Descriptors   Author:  Raymond Hettinger Contact:   Copyright:  Copyright (c) 2003, 2004 Python Software
Foundation. All rights reserved.

Contents

   - Abstract<http://users.rcn.com/python/download/Descriptor.htm#abstract>
   - Definition and
Introduction<http://users.rcn.com/python/download/Descriptor.htm#definition-and-introduction>
   - Descriptor
Protocol<http://users.rcn.com/python/download/Descriptor.htm#descriptor-protocol>
   - Invoking Descriptors<http://users.rcn.com/python/download/Descriptor.htm#invoking-descriptors>
   - Descriptor
Example<http://users.rcn.com/python/download/Descriptor.htm#descriptor-example>
   - Properties<http://users.rcn.com/python/download/Descriptor.htm#properties>
   - Functions and
Methods<http://users.rcn.com/python/download/Descriptor.htm#functions-and-methods>
   - Static Methods and Class
Methods<http://users.rcn.com/python/download/Descriptor.htm#static-methods-and-class-methods>

 Abstract <http://users.rcn.com/python/download/Descriptor.htm#id1>

Defines descriptors, summarizes the protocol, and shows how descriptors are
called. Examines a custom descriptor and several built-in python descriptors
including functions, properties, static methods, and class methods. Shows
how each works by giving a pure Python equivalent and a sample application.

Learning about descriptors not only provides access to a larger toolset, it
creates a deeper understanding of how Python works and an appreciation for
the elegance of its design.
 Definition and
Introduction<http://users.rcn.com/python/download/Descriptor.htm#id2>

In general, a descriptor is an object attribute with "binding behavior", one
whose attribute access has been overridden by methods in the descriptor
protocol. Those methods are __get__, __set__, and __delete__. If any of
those methods are defined for an object, it is said to be a descriptor.

The default behavior for attribute access is to get, set, or delete the
attribute from an object's dictionary. For instance, a.x has a lookup chain
starting with a.__dict__['x'], then type(a).__dict__['x'], and continuing
through the base classes of type(a) excluding metaclasses. If the looked-up
value is an object defining one of the descriptor methods, then Python may
override the default behavior and invoke the descriptor method instead.
Where this occurs in the precedence chain depends on which descriptor
methods were defined. Note that descriptors are only invoked for new style
objects or classes (a class is new style if it inherits from object or type
).

Descriptors are a powerful, general purpose protocol. They are the mechanism
behind properties, methods, static methods, class methods, and super(). They
are used used throughout Python itself to implement the new style classes
introduced in version 2.2. Descriptors simplify the underlying C-code and
offer a flexible set of new tools for everyday Python programs.
 Descriptor Protocol<http://users.rcn.com/python/download/Descriptor.htm#id3>

descr.__get__(self, obj, type=None) --> value

descr.__set__(self, obj, value) --> None

descr.__delete__(self, obj) --> None

That is all there is to it. Define any of these methods and an object is
considered a descriptor and can override default behavior upon being looked
up as an attribute.

If an object defines both __get__ and __set__, it is considered a data
descriptor. Descriptors that only define __get__ are called non-data
descriptors (they are typically used for methods but other uses are
possible).

Data and non-data descriptors differ in how overrides are calculated with
respect to entries in an instance's dictionary. If an instance's dictionary
has an entry with the same name as a data descriptor, the data descriptor
takes precedence. If an instance's dictionary has an entry with the same
name as a non-data descriptor, the dictionary entry takes precedence.

To make a read-only data descriptor, define both __get__ and __set__ with
the __set__ raising an AttributeError when called. Defining the
__set__method with an exception raising placeholder is enough to make
it a data
descriptor.
 Invoking Descriptors<http://users.rcn.com/python/download/Descriptor.htm#id4>

A descriptor can be called directly by its method name. For example,
d.__get__(obj).

Alternatively, it is more common for a descriptor to be invoked
automatically upon attribute access. For example, obj.d looks up d in the
dictionary of obj. If d defines the method __get__, then d.__get__(obj) is
invoked according to the precedence rules listed below.

The details of invocation depend on whether obj is an object or a class.
Either way, descriptors only work for new style objects and classes. A class
is new style if it is a subclass of object.

For objects, the machinery is in object.__getattribute__ which transforms
b.x into type(b).__dict__['x'].__get__(b, type(b)). The implementation works
through a precedence chain that gives data descriptors priority over
instance variables, instance variables priority over non-data descriptors,
and assigns lowest priority to __getattr__ if provided. The full C
implementation can be found in PyObject_GenericGetAttr() in Objects/object.c
.

For classes, the machinery is in type.__getattribute__ which
transforms B.xinto B.__dict__['x'].__get__(None,
B). In pure Python, it looks like:

def __getattribute__(self, key):
    "Emulate type_getattro() in Objects/typeobject.c"
    v = object.__getattribute__(self, key)
    if hasattr(v, '__get__'):
       return v.__get__(None, self)
    return v

The important points to remember are:

   - descriptors are invoked by the __getattribute__ method
   - overriding __getattribute__ prevents automatic descriptor calls
   - __getattribute__ is only available with new style classes and
   objects
   - object.__getattribute__ and type.__getattribute__ make different
   calls to __get__.
   - data descriptors always override instance dictionaries.
   - non-data descriptors may be overridden by instance dictionaries.

The object returned by super() also has a custom __getattribute__ method for
invoking descriptors. The call super(B, obj).m() searches
obj.__class__.__mro__ for the base class A immediately following B and then
returns A.__dict__['m'].__get__(obj, A). If not a descriptor, m is returned
unchanged. If not in the dictionary, m reverts to a search using
object.__getattribute__.

Note, in Python 2.2, super(B, obj).m() would only invoke __get__ if m was a
data descriptor. In Python 2.3, non-data descriptors also get invoked unless
an old-style class is involved. The implementation details are in
super_getattro() in Objects/typeobject.c and a pure Python equivalent can be
found in Guido's
Tutorial<http://www.python.org/2.2.3/descrintro.html#cooperation>
.

The details above show that the mechanism for descriptors is embedded in the
__getattribute__() methods for object, type, and super. Classes inherit this
machinery when they derive from object or if they have a meta-class
providing similar functionality. Likewise, classes can turn-off descriptor
invocation by overriding __getattribute__().
 Descriptor Example<http://users.rcn.com/python/download/Descriptor.htm#id5>

The following code creates a class whose objects are data descriptors which
print a message for each get or set. Overriding __getattribute__ is
alternate approach that could do this for every attribute. However, this
descriptor is useful for monitoring just a few chosen attributes:

class RevealAccess(object):
    """A data descriptor that sets and returns values
       normally and prints a message logging their access.
    """

    def __init__(self, initval=None, name='var'):
        self.val = initval
        self.name = name

    def __get__(self, obj, objtype):
        print 'Retrieving', self.name
        return self.val

    def __set__(self, obj, val):
        print 'Updating' , self.name
        self.val = val

>>> class MyClass(object):
    x = RevealAccess(10, 'var "x"')
    y = 5

>>> m = MyClass()
>>> m.x
Retrieving var "x"
10
>>> m.x = 20
Updating var "x"
>>> m.x
Retrieving var "x"
20
>>> m.y
5

The protocol is simple and offers exciting possibilities. Several use cases
are so common that they have been packaged into individual function calls.
Properties, bound and unbound methods, static methods, and class methods are
all based on the descriptor protocol.
 Properties <http://users.rcn.com/python/download/Descriptor.htm#id6>

Calling property() is a succinct way of building a data descriptor that
triggers function calls upon access to an attribute. Its signature is:

property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

The documentation shows a typical use to define a managed attribute x:

class C(object):
    def getx(self): return self.__x
    def setx(self, value): self.__x = value
    def delx(self): del self.__x
    x = property(getx, setx, delx, "I'm the 'x' property.")

To see how property() is implemented in terms of the descriptor protocol,
here is a pure Python equivalent:

class Property(object):
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError, "unreadable attribute"
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError, "can't set attribute"
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError, "can't delete attribute"
        self.fdel(obj)

The property() builtin helps whenever a user interface has granted attribute
access and then subsequent changes require the intervention of a method.

For instance, a spreadsheet class may grant access to a cell value through
Cell('b10').value. Subsequent improvements to the program require the cell
to be recalculated on every access; however, the programmer does not want to
affect existing client code accessing the attribute directly. The solution
is to wrap access to the value attribute in a property() data descriptor:

class Cell(object):
    . . .
    def getvalue(self, obj):
        "Recalculate cell before returning value"
        self.recalc()
        return obj._value
    value = property(getvalue)

 Functions and Methods<http://users.rcn.com/python/download/Descriptor.htm#id7>

Python's object oriented features are built upon a function based
environment. Using non-data descriptors, the two are merged seamlessly.

Class dictionaries store methods as functions. In a class definition,
methods are written using def and lambda, the usual tools for creating
functions. The only difference from regular functions is that the first
argument is reserved for the object instance. By Python convention, the
instance reference is called self but may be called this or any other
variable name.

To support method calls, functions include the __get__ method for binding
methods during attribute access. This means that all functions are non-data
descriptors which return bound or unbound methods depending whether they are
invoked from an object or a class. In pure python, it works like this:

class Function(object):
    . . .
    def __get__(self, obj, objtype=None):
        "Simulate func_descr_get() in Objects/funcobject.c"
        return types.MethodType(self, obj, objtype)

Running the interpreter shows how the function descriptor works in practice:

>>> class D(object):
     def f(self, x):
          return x

>>> d = D()
>>> D.__dict__['f'] # Stored internally as a function

>>> D.f             # Get from a class becomes an unbound method

>>> d.f             # Get from an instance becomes a bound method
<__main__.D object at 0x00B18C90>>

The output suggests that bound and unbound methods are two different types.
While they could have been implemented that way, the actual C implemention
of PyMethod_Type in Objects/classobject.c is a single object with two
different representations depending on whether the im_self field is set or
is NULL (the C equivalent of None).

Likewise, the effects of calling a method object depend on the
im_selffield. If set (meaning bound), the original function (stored in
the
im_func field) is called as expected with the first argument set to the
instance. If unbound, all of the arguments are passed unchanged to the
original function. The actual C implementation of instancemethod_call() is
only slightly more complex in that it includes some type checking.
 Static Methods and Class
Methods<http://users.rcn.com/python/download/Descriptor.htm#id8>

Non-data descriptors provide a simple mechanism for variations on the usual
patterns of binding functions into methods.

To recap, functions have a __get__ method so that they can be converted to a
method when accessed as attributes. The non-data descriptor transforms a
obj.f(*args) call into f(obj, *args). Calling klass.f(*args) becomes
f(*args).

This chart summarizes the binding and its two most useful variants:

    Transformation   Called from an Object Called from a Class  Descriptor
function f(obj, *args) f(*args) staticmethod f(*args) f(*args)
classmethod f(type(obj),
*args) f(klass, *args)

Static methods return the underlying function without changes. Calling
either c.f or C.f is the equivalent of a direct lookup into
object.__getattribute__(c,
"f") or object.__getattribute__(C, "f"). As a result, the function becomes
identically accessible from either an object or a class.

Good candidates for static methods are methods that do not reference the
self variable.

For instance, a statistics package may include a container class for
experimental data. The class provides normal methods for computing the
average, mean, median, and other descriptive statistics that depend on the
data. However, there may be useful functions which are conceptually related
but do not depend on the data. For instance, erf(x) is handy conversion
routine that comes up in statistical work but does not directly depend on a
particular data set. It can be called either from an object or the class:
s.erf(1.5) --> .9332 or Sample.erf(1.5) --> .9332.

Since staticmethods return the underlying function with no changes, the
example calls are unexciting:

>>> class E(object):
     def f(x):
          print x
     f = staticmethod(f)

>>> print E.f(3)
3
>>> print E().f(3)
3

Using the non-data descriptor protocol, a pure Python version of
staticmethod() would look like this:

class StaticMethod(object):
 "Emulate PyStaticMethod_Type() in Objects/funcobject.c"

 def __init__(self, f):
      self.f = f

 def __get__(self, obj, objtype=None):
      return self.f

Unlike static methods, class methods prepend the class reference to the
argument list before calling the function. This format is the same for
whether the caller is an object or a class:

>>> class E(object):
     def f(klass, x):
          return klass.__name__, x
     f = classmethod(f)

>>> print E.f(3)
('E', 3)
>>> print E().f(3)
('E', 3)

This behavior is useful whenever the function only needs to have a class
reference and does not care about any underlying data. One use for
classmethods is to create alternate class constructors. In Python 2.3, the
classmethod dict.fromkeys() creates a new dictionary from a list of keys.
The pure Python equivalent is:

class Dict:
    . . .
    def fromkeys(klass, iterable, value=None):
        "Emulate dict_fromkeys() in Objects/dictobject.c"
        d = klass()
        for key in iterable:
            d[key] = value
        return d
    fromkeys = classmethod(fromkeys)

Now a new dictionary of unique keys can be constructed like this:

>>> Dict.fromkeys('abracadabra')
{'a': None, 'r': None, 'b': None, 'c': None, 'd': None}

Using the non-data descriptor protocol, a pure Python version of
classmethod() would look like this:

class ClassMethod(object):
     "Emulate PyClassMethod_Type() in Objects/funcobject.c"

     def __init__(self, f):
          self.f = f

     def __get__(self, obj, klass=None):
          if klass is None:
               klass = type(obj)
          def newfunc(*args):
               return self.f(klass, *args)
          return newfunc
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070114/a61e116e/attachment-0001.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年01月14日 星期日 02:06

Gao Hong joy.highland在gmail.com
星期日 一月 14 02:06:36 HKT 2007

лл£¬ÎÒ˵˵ÎÒ¿´¹ýµÄÀí½â£¬ÕâÆäÖÐÕªÁËһЩ»°£º

   -

   In general, a descriptor is an object attribute with "binding
   behavior", one whose attribute access has been overridden by methods in the
   descriptor protocol. Those methods are __get__, __set__, and
   __delete__. If any of those methods are defined for an object, it is
   said to be a descriptor.


£¨×ܵÄÀ´Ëµ£¬descriptorÊÇÕâÑùÒ»Àà¶ÔÏó£¬ËûÃǵÄÊôÐÔ±»°ó¶¨ÁËÌØÊâµÄÐÐΪ£¬Ö»Òª¶¨ÒåÁË__get__,__set__,__delete__ÕâÈý¸öº¯ÊýÖеÄÆäÖÐÒ»¸ö£¬Õâ¸ö¶ÔÏó¾ÍÊÇdescriptor£©
¶ÔÓÚÒ»°ãµÄ¶ÔÏó»òÀ࣬ËûÃǶÔÓÚÊôÐԵĶÁдÊÇͨ¹ýdict[]ÖеļüÀ´Ë÷Òý·ÃÎÊ£¬µ«Èç¹ûÇ°ÃæÌáµ½µÄÈκÎÒ»¸öº¯ÊýÔÚÕâ¸öÀàÖб»ÊµÏÖÁË£¬ÄÇô¾Í»áµ÷ÓÃÆäÏàÓ¦µÄ·½·¨£¬
´Ëʱ¾ÍÊÇÊôÓÚdescriptor.×¢£ºdescriptorÖ»ÊÊÓÃÓÚnew style class.


   -

   If an object defines both __get__ and __set__, it is considered a data
   descriptor. Descriptors that only define __get__ are called non-data
   descriptors (they are typically used for methods but other uses are
   possible).Data and non-data descriptors differ in how overrides are
   calculated with respect to entries in an instance's dictionary. If an
   instance's dictionary has an entry with the same name as a data descriptor,
   the data descriptor takes precedence. If an instance's dictionary has an
   entry with the same name as a non-data descriptor, the dictionary entry
   takes precedence.

 ÓÐÁ½Ààdescriptor¡£non-data descriptors£ºÖ»¶¨ÒåÁË__get__·½·¨¡£data
descriptor£ºÍ¬Ê±¶¨ÒåÁË__get__ºÍ__set__·½·¨¡£data descriptor»áÌæ´údictÊôÐÔË÷Òý£¬¶ønon-data
descriptor²»»áÌæ´úË÷Òý¼üÖµ¡£


   -

   def __getattribute__(self, key):
       "Emulate type_getattro() in Objects/typeobject.c"
       v = object.__getattribute__(self, key)
       if hasattr(v, '__get__'):
          return v.__get__(None, self)
       return v

   The important points to remember are:
    - descriptors are invoked by the __getattribute__ method
      - overriding __getattribute__ prevents automatic descriptor
      calls
      - __getattribute__ is only available with new style classes and
      objects
      - object.__getattribute__ and type.__getattribute__ make
      different calls to __get__.
      - data descriptors always override instance dictionaries.
      - non-data descriptors may be overridden by instance
      dictionaries.

 DescriptorµÄ»úÖÆÖ÷ÒªÊÇͨ¹ý__getattribute__º¯ÊýÀ´ÊµÏÖ£¬¶ÔÓÚÀàºÍ¶ÔÏó__getattribute__×ö²»Í¬µÄ´¦Àí¡£
non-data descriptors may be overridden by instance dictionaries.

Õâ¸öÎÒ²»Ì«Àí½â£¬ÎªÊ²Ã´ÄØ£¿ÓÐ__getattribute__º¯Êý£¬ÄÇôÊDz»ÊÇÒ²ÓÐÏàÓ¦µÄ__setattribute__º¯ÊýÀ´ÊµÏÖ__set__
descriptor»úÖÆÄØ£¿

ÔÚ07-1-14£¬Í·Ì«ÔÎ <torrycn在gmail.com> дµÀ£º

>
>
> ÔÚ07-1-14£¬Gao Hong <joy.highland在gmail.com> дµÀ£º
> >
> > ²»ºÃÒâ˼£¬ÎÒÕâÀïÉϲ»È¥£¬ÄÜ°ïÎÒתһÏÂÂð£¿
>
>
> ÎÒ°ïÄãתһÏ°ɡ£ºÜ³¤ºÜ³¤¡£¡£¡£
>
>  How-To Guide for Descriptors    Author:  Raymond Hettinger Contact:  > at rcn dot com> Copyright:  Copyright (c) 2003, 2004 Python Software
> Foundation. All rights reserved.
>
> Contents
>
>    - Abstract<http://users.rcn.com/python/download/Descriptor.htm#abstract>
>    - Definition and Introduction<http://users.rcn.com/python/download/Descriptor.htm#definition-and-introduction>
>    - Descriptor Protocol<http://users.rcn.com/python/download/Descriptor.htm#descriptor-protocol>
>    - Invoking Descriptors<http://users.rcn.com/python/download/Descriptor.htm#invoking-descriptors>
>    - Descriptor Example<http://users.rcn.com/python/download/Descriptor.htm#descriptor-example>
>    - Properties<http://users.rcn.com/python/download/Descriptor.htm#properties>
>    - Functions and Methods<http://users.rcn.com/python/download/Descriptor.htm#functions-and-methods>
>    - Static Methods and Class Methods<http://users.rcn.com/python/download/Descriptor.htm#static-methods-and-class-methods>
>
>  Abstract <http://users.rcn.com/python/download/Descriptor.htm#id1>
>
> Defines descriptors, summarizes the protocol, and shows how descriptors
> are called. Examines a custom descriptor and several built-in python
> descriptors including functions, properties, static methods, and class
> methods. Shows how each works by giving a pure Python equivalent and a
> sample application.
>
> Learning about descriptors not only provides access to a larger toolset,
> it creates a deeper understanding of how Python works and an appreciation
> for the elegance of its design.
>  Definition and Introduction<http://users.rcn.com/python/download/Descriptor.htm#id2>
>
> In general, a descriptor is an object attribute with "binding behavior",
> one whose attribute access has been overridden by methods in the descriptor
> protocol. Those methods are __get__, __set__, and __delete__. If any of
> those methods are defined for an object, it is said to be a descriptor.
>
> The default behavior for attribute access is to get, set, or delete the
> attribute from an object's dictionary. For instance, a.x has a lookup
> chain starting with a.__dict__['x'], then type(a).__dict__['x'], and
> continuing through the base classes of type(a) excluding metaclasses. If
> the looked-up value is an object defining one of the descriptor methods,
> then Python may override the default behavior and invoke the descriptor
> method instead. Where this occurs in the precedence chain depends on which
> descriptor methods were defined. Note that descriptors are only invoked for
> new style objects or classes (a class is new style if it inherits from
> object or type).
>
> Descriptors are a powerful, general purpose protocol. They are the
> mechanism behind properties, methods, static methods, class methods, and
> super(). They are used used throughout Python itself to implement the new
> style classes introduced in version 2.2. Descriptors simplify the
> underlying C-code and offer a flexible set of new tools for everyday Python
> programs.
>  Descriptor Protocol<http://users.rcn.com/python/download/Descriptor.htm#id3>
>
> descr.__get__(self, obj, type=None) --> value
>
> descr.__set__(self, obj, value) --> None
>
> descr.__delete__(self, obj) --> None
>
> That is all there is to it. Define any of these methods and an object is
> considered a descriptor and can override default behavior upon being looked
> up as an attribute.
>
> If an object defines both __get__ and __set__, it is considered a data
> descriptor. Descriptors that only define __get__ are called non-data
> descriptors (they are typically used for methods but other uses are
> possible).
>
> Data and non-data descriptors differ in how overrides are calculated with
> respect to entries in an instance's dictionary. If an instance's dictionary
> has an entry with the same name as a data descriptor, the data descriptor
> takes precedence. If an instance's dictionary has an entry with the same
> name as a non-data descriptor, the dictionary entry takes precedence.
>
> To make a read-only data descriptor, define both __get__ and __set__ with
> the __set__ raising an AttributeError when called. Defining the __set__method with an exception raising placeholder is enough to make it a data
> descriptor.
>  Invoking Descriptors<http://users.rcn.com/python/download/Descriptor.htm#id4>
>
> A descriptor can be called directly by its method name. For example,
> d.__get__(obj).
>
> Alternatively, it is more common for a descriptor to be invoked
> automatically upon attribute access. For example, obj.d looks up d in the
> dictionary of obj. If d defines the method __get__, then d.__get__(obj) is
> invoked according to the precedence rules listed below.
>
> The details of invocation depend on whether obj is an object or a class.
> Either way, descriptors only work for new style objects and classes. A class
> is new style if it is a subclass of object.
>
> For objects, the machinery is in object.__getattribute__ which transforms
> b.x into type(b).__dict__['x'].__get__(b, type(b)). The implementation
> works through a precedence chain that gives data descriptors priority over
> instance variables, instance variables priority over non-data descriptors,
> and assigns lowest priority to __getattr__ if provided. The full C
> implementation can be found in PyObject_GenericGetAttr() in
> Objects/object.c.
>
> For classes, the machinery is in type.__getattribute__ which transforms
> B.x into B.__dict__['x'].__get__(None, B). In pure Python, it looks like:
>
> def __getattribute__(self, key):
>     "Emulate type_getattro() in Objects/typeobject.c"
>     v = object.__getattribute__(self, key)
>     if hasattr(v, '__get__'):
>        return v.__get__(None, self)
>     return v
>
> The important points to remember are:
>
>    - descriptors are invoked by the __getattribute__ method
>    - overriding __getattribute__ prevents automatic descriptor calls
>    - __getattribute__ is only available with new style classes and
>    objects
>    - object.__getattribute__ and type.__getattribute__ make different
>    calls to __get__.
>    - data descriptors always override instance dictionaries.
>    - non-data descriptors may be overridden by instance dictionaries.
>
> The object returned by super() also has a custom __getattribute__ method
> for invoking descriptors. The call super(B, obj).m() searches
> obj.__class__.__mro__ for the base class A immediately following B and
> then returns A.__dict__['m'].__get__(obj, A). If not a descriptor, m is
> returned unchanged. If not in the dictionary, m reverts to a search using
> object.__getattribute__.
>
> Note, in Python 2.2, super(B, obj).m() would only invoke __get__ if m was
> a data descriptor. In Python 2.3, non-data descriptors also get invoked
> unless an old-style class is involved. The implementation details are in
> super_getattro() in Objects/typeobject.c and a pure Python equivalent can
> be found in Guido's Tutorial<http://www.python.org/2.2.3/descrintro.html#cooperation>
> .
>
> The details above show that the mechanism for descriptors is embedded in
> the __getattribute__() methods for object, type, and super. Classes
> inherit this machinery when they derive from object or if they have a
> meta-class providing similar functionality. Likewise, classes can turn-off
> descriptor invocation by overriding __getattribute__().
>  Descriptor Example<http://users.rcn.com/python/download/Descriptor.htm#id5>
>
> The following code creates a class whose objects are data descriptors
> which print a message for each get or set. Overriding __getattribute__ is
> alternate approach that could do this for every attribute. However, this
> descriptor is useful for monitoring just a few chosen attributes:
>
> class RevealAccess(object):
>     """A data descriptor that sets and returns values
>        normally and prints a message logging their access.
>     """
>
>
>     def __init__(self, initval=None, name='var'):
>         self.val = initval
>         self.name = name
>
>     def __get__(self, obj, objtype):
>         print 'Retrieving', self.name
>         return self.val
>
>     def __set__(self, obj, val):
>         print 'Updating' , self.name
>         self.val = val
>
> >>> class MyClass(object):
>     x = RevealAccess(10, 'var "x"')
>     y = 5
>
> >>> m = MyClass()
> >>> m.x
> Retrieving var "x"
> 10
> >>> m.x = 20
> Updating var "x"
>
> >>> m.x
> Retrieving var "x"
> 20
> >>> m.y
> 5
>
> The protocol is simple and offers exciting possibilities. Several use
> cases are so common that they have been packaged into individual function
> calls. Properties, bound and unbound methods, static methods, and class
> methods are all based on the descriptor protocol.
> --
> It's a long journey to go!
>
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070114/92ba6210/attachment-0001.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年01月14日 星期日 16:00

yi huang yi.codeplayer在gmail.com
星期日 一月 14 16:00:42 HKT 2007

On 1/14/07, Gao Hong <joy.highland at gmail.com> wrote:
>
> 谢谢,我说说我看过的理解,这其中摘了一些话:
>
>    -
>
>    In general, a descriptor is an object attribute with "binding
>    behavior", one whose attribute access has been overridden by methods in the
>    descriptor protocol. Those methods are __get__ , __set__, and
>    __delete__. If any of those methods are defined for an object, it is
>    said to be a descriptor.
>
>
> (总的来说,descriptor是这样一类对象,他们的属性被绑定了特殊的行为,只要定义了__get__,__set__,__delete__这三个函数中的其中一个,这个对象就是descriptor)
> 对于一般的对象或类,他们对于属性的读写是通过dict[]中的键来索引访问,但如果前面提到的任何一个函数在这个类中被实现了,那么就会调用其相应的方法,
> 此时就是属于descriptor.注:descriptor只适用于new style class.
>
>
>    -
>
>    If an object defines both __get__ and __set__, it is considered a
>    data descriptor. Descriptors that only define __get__ are called
>    non-data descriptors (they are typically used for methods but other uses are
>    possible).Data and non-data descriptors differ in how overrides are
>    calculated with respect to entries in an instance's dictionary. If an
>    instance's dictionary has an entry with the same name as a data descriptor,
>    the data descriptor takes precedence. If an instance's dictionary has an
>    entry with the same name as a non-data descriptor, the dictionary entry
>    takes precedence.
>
>  有两类descriptor。non-data descriptors:只定义了__get__方法。data
> descriptor:同时定义了__get__和__set__方法。data descriptor会替代dict属性索引,而non-data
> descriptor不会替代索引键值。
>
>
>    -
>
>    def __getattribute__(self, key):
>        "Emulate type_getattro() in Objects/typeobject.c"
>        v = object.__getattribute__(self, key)
>
>
>        if hasattr(v, '__get__'):
>           return v.__get__(None, self)
>
>        return v
>
>    The important points to remember are:
>     - descriptors are invoked by the __getattribute__ method
>       - overriding __getattribute__ prevents automatic descriptor
>       calls
>       - __getattribute__ is only available with new style classes
>       and objects
>       - object.__getattribute__ and type.__getattribute__ make
>       different calls to __get__.
>       - data descriptors always override instance dictionaries.
>       - non-data descriptors may be overridden by instance
>       dictionaries.
>
>  Descriptor的机制主要是通过__getattribute__函数来实现,对于类和对象__getattribute__做不同的处理。
> non-data descriptors may be overridden by instance dictionaries.
>
> 这个我不太理解,为什么呢?有__getattribute__函数,那么是不是也有相应的__setattribute__函数来实现__set__
> descriptor机制呢?
>
> 在07-1-14,头太晕 <torrycn at gmail.com> 写道:
>
> >
> >
> > 在07-1-14,Gao Hong < joy.highland at gmail.com > 写道:
> > >
> > > 不好意思,我这里上不去,能帮我转一下吗?
> >
> >
> > 我帮你转一下吧。很长很长。。。
> >
> >  How-To Guide for Descriptors    Author:  Raymond Hettinger Contact:  > > at rcn dot com> Copyright:  Copyright (c) 2003, 2004 Python Software
> > Foundation. All rights reserved.
> >
> > Contents
> >
> >    - Abstract<http://users.rcn.com/python/download/Descriptor.htm#abstract>
> >    - Definition and Introduction<http://users.rcn.com/python/download/Descriptor.htm#definition-and-introduction>
> >    - Descriptor Protocol<http://users.rcn.com/python/download/Descriptor.htm#descriptor-protocol>
> >    - Invoking Descriptors<http://users.rcn.com/python/download/Descriptor.htm#invoking-descriptors>
> >    - Descriptor Example<http://users.rcn.com/python/download/Descriptor.htm#descriptor-example>
> >    - Properties<http://users.rcn.com/python/download/Descriptor.htm#properties>
> >    - Functions and Methods<http://users.rcn.com/python/download/Descriptor.htm#functions-and-methods>
> >    - Static Methods and Class Methods<http://users.rcn.com/python/download/Descriptor.htm#static-methods-and-class-methods>
> >
> >  Abstract <http://users.rcn.com/python/download/Descriptor.htm#id1>
> >
> > Defines descriptors, summarizes the protocol, and shows how descriptors
> > are called. Examines a custom descriptor and several built-in python
> > descriptors including functions, properties, static methods, and class
> > methods. Shows how each works by giving a pure Python equivalent and a
> > sample application.
> >
> > Learning about descriptors not only provides access to a larger toolset,
> > it creates a deeper understanding of how Python works and an appreciation
> > for the elegance of its design.
> >  Definition and Introduction<http://users.rcn.com/python/download/Descriptor.htm#id2>
> >
> > In general, a descriptor is an object attribute with "binding behavior",
> > one whose attribute access has been overridden by methods in the descriptor
> > protocol. Those methods are __get__, __set__ , and __delete__. If any of
> > those methods are defined for an object, it is said to be a descriptor.
> >
> > The default behavior for attribute access is to get, set, or delete the
> > attribute from an object's dictionary. For instance, a.x has a lookup
> > chain starting with a.__dict__['x'], then type(a).__dict__['x'], and
> > continuing through the base classes of type(a) excluding metaclasses. If
> > the looked-up value is an object defining one of the descriptor methods,
> > then Python may override the default behavior and invoke the descriptor
> > method instead. Where this occurs in the precedence chain depends on which
> > descriptor methods were defined. Note that descriptors are only invoked for
> > new style objects or classes (a class is new style if it inherits from
> > object or type).
> >
> > Descriptors are a powerful, general purpose protocol. They are the
> > mechanism behind properties, methods, static methods, class methods, and
> > super(). They are used used throughout Python itself to implement the
> > new style classes introduced in version 2.2. Descriptors simplify the
> > underlying C-code and offer a flexible set of new tools for everyday Python
> > programs.
> >  Descriptor Protocol<http://users.rcn.com/python/download/Descriptor.htm#id3>
> >
> > descr.__get__(self, obj, type=None) --> value
> >
> > descr.__set__(self, obj, value) --> None
> >
> > descr.__delete__(self, obj) --> None
> >
> > That is all there is to it. Define any of these methods and an object is
> > considered a descriptor and can override default behavior upon being looked
> > up as an attribute.
> >
> > If an object defines both __get__ and __set__, it is considered a data
> > descriptor. Descriptors that only define __get__ are called non-data
> > descriptors (they are typically used for methods but other uses are
> > possible).
> >
> > Data and non-data descriptors differ in how overrides are calculated
> > with respect to entries in an instance's dictionary. If an instance's
> > dictionary has an entry with the same name as a data descriptor, the data
> > descriptor takes precedence. If an instance's dictionary has an entry with
> > the same name as a non-data descriptor, the dictionary entry takes
> > precedence.
> >
> > To make a read-only data descriptor, define both __get__ and __set__with the
> > __set__ raising an AttributeError when called. Defining the __set__method with an exception raising placeholder is enough to make it a data
> > descriptor.
> >  Invoking Descriptors<http://users.rcn.com/python/download/Descriptor.htm#id4>
> >
> > A descriptor can be called directly by its method name. For example,
> > d.__get__(obj).
> >
> > Alternatively, it is more common for a descriptor to be invoked
> > automatically upon attribute access. For example, obj.d looks up d in
> > the dictionary of obj. If d defines the method __get__, then
> > d.__get__(obj) is invoked according to the precedence rules listed
> > below.
> >
> > The details of invocation depend on whether obj is an object or a class.
> > Either way, descriptors only work for new style objects and classes. A class
> > is new style if it is a subclass of object.
> >
> > For objects, the machinery is in object.__getattribute__ which
> > transforms b.x into type(b).__dict__['x'].__get__(b, type(b)). The
> > implementation works through a precedence chain that gives data descriptors
> > priority over instance variables, instance variables priority over non-data
> > descriptors, and assigns lowest priority to __getattr__ if provided. The
> > full C implementation can be found in PyObject_GenericGetAttr() in
> > Objects/object.c.
> >
> > For classes, the machinery is in type.__getattribute__ which transforms
> > B.x into B.__dict__['x'].__get__(None, B). In pure Python, it looks
> > like:
> >
> > def __getattribute__(self, key):
> >
> >
> >     "Emulate type_getattro() in Objects/typeobject.c"
> >     v = object.__getattribute__(self, key)
> >     if hasattr(v, '__get__'):
> >        return v.__get__(None, self)
> >
> >     return v
> >
> > The important points to remember are:
> >
> >    - descriptors are invoked by the __getattribute__ method
> >    - overriding __getattribute__ prevents automatic descriptor calls
> >    - __getattribute__ is only available with new style classes and
> >    objects
> >    - object.__getattribute__ and type.__getattribute__ make different
> >    calls to __get__.
> >    - data descriptors always override instance dictionaries.
> >    - non-data descriptors may be overridden by instance dictionaries.
> >
> > The object returned by super() also has a custom __getattribute__ method
> > for invoking descriptors. The call super(B, obj).m() searches
> > obj.__class__.__mro__ for the base class A immediately following B and
> > then returns A.__dict__['m'].__get__(obj, A). If not a descriptor, m is
> > returned unchanged. If not in the dictionary, m reverts to a search
> > using object.__getattribute__.
> >
> > Note, in Python 2.2, super(B, obj).m() would only invoke __get__ if mwas a data descriptor. In Python
> > 2.3, non-data descriptors also get invoked unless an old-style class is
> > involved. The implementation details are in super_getattro() in
> > Objects/typeobject.c and a pure Python equivalent can be found in Guido's
> > Tutorial <http://www.python.org/2.2.3/descrintro.html#cooperation>.
> >
> > The details above show that the mechanism for descriptors is embedded in
> > the __getattribute__() methods for object, type, and super. Classes
> > inherit this machinery when they derive from object or if they have a
> > meta-class providing similar functionality. Likewise, classes can turn-off
> > descriptor invocation by overriding __getattribute__().
> >  Descriptor Example<http://users.rcn.com/python/download/Descriptor.htm#id5>
> >
> > The following code creates a class whose objects are data descriptors
> > which print a message for each get or set. Overriding __getattribute__is alternate approach that could do this for every attribute. However, this
> > descriptor is useful for monitoring just a few chosen attributes:
> >
> > class RevealAccess(object):
> >     """A data descriptor that sets and returns values
> >        normally and prints a message logging their access.
> >     """
> >
> >
> >     def __init__(self, initval=None, name='var'):
> >         self.val = initval
> >         self.name = name
> >
> >
> >     def __get__(self, obj, objtype):
> >         print 'Retrieving',
> > self.name
> >         return self.val
> >
> >
> >     def __set__(self, obj, val):
> >         print 'Updating' ,
> > self.name
> >         self.val = val
> >
> > >>> class MyClass(object):
> >
> >     x = RevealAccess(10, 'var "x"')
> >     y = 5
> >
> > >>> m = MyClass()
> > >>> m.x
> > Retrieving var "x"
> >
> > 10
> > >>> m.x = 20
> > Updating var "x"
> >
> >
> > >>> m.x
> > Retrieving var "x"
> > 20
> > >>> m.y
> > 5
> >
> > The protocol is simple and offers exciting possibilities. Several use
> > cases are so common that they have been packaged into individual function
> > calls. Properties, bound and unbound methods, static methods, and class
> > methods are all based on the descriptor protocol.
> > --
> > It's a long journey to go!
> >
>
> _______________________________________________
> python-chinese
> Post: send python-chinese at lists.python.cn
> Subscribe: send subscribe to python-chinese-request at lists.python.cn
> Unsubscribe: send unsubscribe to   python-chinese-request at lists.python.cn
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
>

你还需要很仔细地看下这个:attribute查找策略<http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#id822546>
另外也向你推荐下我这篇blog:理解 python 的 method 和 function 兼谈
descriptor<http://codeplayer.blogspot.com/2006/12/python-method-function-descriptor.html>;-)

-- 
http://codeplayer.blogspot.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://python.cn/pipermail/python-chinese/attachments/20070114/da51087f/attachment-0001.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2007年01月14日 星期日 20:40

Gao Hong joy.highland在gmail.com
星期日 一月 14 20:40:17 HKT 2007

ÄãµÃblogÀïдµÃºÜÉî¿Ì£¬µ«ÎÒÓÐһЩ¶«Î÷»¹ÊDz»Ì«Ã÷°×£¬»¹ÐèÒªÔÙ¿´Ò»¿´

2007/1/14, yi huang <yi.codeplayer在gmail.com>:
>
> On 1/14/07, Gao Hong <joy.highland在gmail.com> wrote:
>
> >  лл£¬ÎÒ˵˵ÎÒ¿´¹ýµÄÀí½â£¬ÕâÆäÖÐÕªÁËһЩ»°£º
> >
> >    -
> >
> >    In general, a descriptor is an object attribute with "binding
> >    behavior", one whose attribute access has been overridden by methods in the
> >    descriptor protocol. Those methods are __get__ , __set__, and
> >    __delete__. If any of those methods are defined for an object, it
> >    is said to be a descriptor.
> >
> >
> > £¨×ܵÄÀ´Ëµ£¬descriptorÊÇÕâÑùÒ»Àà¶ÔÏó£¬ËûÃǵÄÊôÐÔ±»°ó¶¨ÁËÌØÊâµÄÐÐΪ£¬Ö»Òª¶¨ÒåÁË__get__,__set__,__delete__ÕâÈý¸öº¯ÊýÖеÄÆäÖÐÒ»¸ö£¬Õâ¸ö¶ÔÏó¾ÍÊÇdescriptor£©
> >
> > ¶ÔÓÚÒ»°ãµÄ¶ÔÏó»òÀ࣬ËûÃǶÔÓÚÊôÐԵĶÁдÊÇͨ¹ýdict[]ÖеļüÀ´Ë÷Òý·ÃÎÊ£¬µ«Èç¹ûÇ°ÃæÌáµ½µÄÈκÎÒ»¸öº¯ÊýÔÚÕâ¸öÀàÖб»ÊµÏÖÁË£¬ÄÇô¾Í»áµ÷ÓÃÆäÏàÓ¦µÄ·½·¨£¬
> > ´Ëʱ¾ÍÊÇÊôÓÚdescriptor.×¢£ºdescriptorÖ»ÊÊÓÃÓÚnew style class.
> >
> >
> >    -
> >
> >    If an object defines both __get__ and __set__, it is considered a
> >    data descriptor. Descriptors that only define __get__ are called
> >    non-data descriptors (they are typically used for methods but other uses are
> >    possible).Data and non-data descriptors differ in how overrides are
> >    calculated with respect to entries in an instance's dictionary. If an
> >    instance's dictionary has an entry with the same name as a data descriptor,
> >    the data descriptor takes precedence. If an instance's dictionary has an
> >    entry with the same name as a non-data descriptor, the dictionary entry
> >    takes precedence.
> >
> >  ÓÐÁ½Ààdescriptor¡£non-data descriptors£ºÖ»¶¨ÒåÁË__get__·½·¨¡£data
> > descriptor£ºÍ¬Ê±¶¨ÒåÁË__get__ºÍ__set__·½·¨¡£data descriptor»áÌæ´údictÊôÐÔË÷Òý£¬¶ønon-data
> > descriptor²»»áÌæ´úË÷Òý¼üÖµ¡£
> >
> >
> >    -
> >
> >    def __getattribute__(self, key):
> >        "Emulate type_getattro() in Objects/typeobject.c"
> >        v = object.__getattribute__(self, key)
> >
> >
> >
> >        if hasattr(v, '__get__'):
> >           return v.__get__(None, self)
> >
> >        return v
> >
> >    The important points to remember are:
> >     - descriptors are invoked by the __getattribute__ method
> >       - overriding __getattribute__ prevents automatic descriptor
> >       calls
> >       - __getattribute__ is only available with new style classes
> >       and objects
> >       - object.__getattribute__ and type.__getattribute__ make
> >       different calls to __get__.
> >       - data descriptors always override instance dictionaries.
> >       - non-data descriptors may be overridden by instance
> >       dictionaries.
> >
> >  DescriptorµÄ»úÖÆÖ÷ÒªÊÇͨ¹ý__getattribute__º¯ÊýÀ´ÊµÏÖ£¬¶ÔÓÚÀàºÍ¶ÔÏó__getattribute__×ö²»Í¬µÄ´¦Àí¡£
> > non-data descriptors may be overridden by instance dictionaries.
> >
> > Õâ¸öÎÒ²»Ì«Àí½â£¬ÎªÊ²Ã´ÄØ£¿ÓÐ__getattribute__º¯Êý£¬ÄÇôÊDz»ÊÇÒ²ÓÐÏàÓ¦µÄ__setattribute__º¯ÊýÀ´ÊµÏÖ__set__
> > descriptor»úÖÆÄØ£¿
> >
> > ÔÚ07-1-14£¬Í·Ì«ÔÎ <torrycn在gmail.com> дµÀ£º
> >
> > >
> > >
> > >  ÔÚ07-1-14£¬Gao Hong < joy.highland在gmail.com > дµÀ£º
> > > >
> > > > ²»ºÃÒâ˼£¬ÎÒÕâÀïÉϲ»È¥£¬ÄÜ°ïÎÒתһÏÂÂð£¿
> > >
> > >
> > > ÎÒ°ïÄãתһÏ°ɡ£ºÜ³¤ºÜ³¤¡£¡£¡£
> > >
> > >  How-To Guide for Descriptors    Author:  Raymond Hettinger Contact:  > > > at rcn dot com> Copyright:  Copyright (c) 2003, 2004 Python Software
> > > Foundation. All rights reserved.
> > >
> > > Contents
> > >
> > >    - Abstract<http://users.rcn.com/python/download/Descriptor.htm#abstract>
> > >    - Definition and Introduction<http://users.rcn.com/python/download/Descriptor.htm#definition-and-introduction>
> > >    - Descriptor Protocol<http://users.rcn.com/python/download/Descriptor.htm#descriptor-protocol>
> > >    - Invoking Descriptors<http://users.rcn.com/python/download/Descriptor.htm#invoking-descriptors>
> > >    - Descriptor Example<http://users.rcn.com/python/download/Descriptor.htm#descriptor-example>
> > >    - Properties<http://users.rcn.com/python/download/Descriptor.htm#properties>
> > >    - Functions and Methods<http://users.rcn.com/python/download/Descriptor.htm#functions-and-methods>
> > >    - Static Methods and Class Methods<http://users.rcn.com/python/download/Descriptor.htm#static-methods-and-class-methods>
> > >
> > >  Abstract <http://users.rcn.com/python/download/Descriptor.htm#id1>
> > >
> > > Defines descriptors, summarizes the protocol, and shows how
> > > descriptors are called. Examines a custom descriptor and several built-in
> > > python descriptors including functions, properties, static methods, and
> > > class methods. Shows how each works by giving a pure Python equivalent and a
> > > sample application.
> > >
> > > Learning about descriptors not only provides access to a larger
> > > toolset, it creates a deeper understanding of how Python works and an
> > > appreciation for the elegance of its design.
> > >  Definition and Introduction<http://users.rcn.com/python/download/Descriptor.htm#id2>
> > >
> > > In general, a descriptor is an object attribute with "binding
> > > behavior", one whose attribute access has been overridden by methods in the
> > > descriptor protocol. Those methods are __get__, __set__ , and
> > > __delete__. If any of those methods are defined for an object, it is
> > > said to be a descriptor.
> > >
> > > The default behavior for attribute access is to get, set, or delete
> > > the attribute from an object's dictionary. For instance, a.x has a
> > > lookup chain starting with a.__dict__['x'], then type(a).__dict__['x'],
> > > and continuing through the base classes of type(a) excluding
> > > metaclasses. If the looked-up value is an object defining one of the
> > > descriptor methods, then Python may override the default behavior and invoke
> > > the descriptor method instead. Where this occurs in the precedence chain
> > > depends on which descriptor methods were defined. Note that descriptors are
> > > only invoked for new style objects or classes (a class is new style if it
> > > inherits from object or type).
> > >
> > > Descriptors are a powerful, general purpose protocol. They are the
> > > mechanism behind properties, methods, static methods, class methods, and
> > > super(). They are used used throughout Python itself to implement the
> > > new style classes introduced in version 2.2. Descriptors simplify the
> > > underlying C-code and offer a flexible set of new tools for everyday Python
> > > programs.
> > >  Descriptor Protocol<http://users.rcn.com/python/download/Descriptor.htm#id3>
> > >
> > > descr.__get__(self, obj, type=None) --> value
> > >
> > > descr.__set__(self, obj, value) --> None
> > >
> > > descr.__delete__(self, obj) --> None
> > >
> > > That is all there is to it. Define any of these methods and an object
> > > is considered a descriptor and can override default behavior upon being
> > > looked up as an attribute.
> > >
> > > If an object defines both __get__ and __set__, it is considered a data
> > > descriptor. Descriptors that only define __get__ are called non-data
> > > descriptors (they are typically used for methods but other uses are
> > > possible).
> > >
> > > Data and non-data descriptors differ in how overrides are calculated
> > > with respect to entries in an instance's dictionary. If an instance's
> > > dictionary has an entry with the same name as a data descriptor, the data
> > > descriptor takes precedence. If an instance's dictionary has an entry with
> > > the same name as a non-data descriptor, the dictionary entry takes
> > > precedence.
> > >
> > > To make a read-only data descriptor, define both __get__ and __set__with the
> > > __set__ raising an AttributeError when called. Defining the __set__method with an exception raising placeholder is enough to make it a data
> > > descriptor.
> > >  Invoking Descriptors<http://users.rcn.com/python/download/Descriptor.htm#id4>
> > >
> > > A descriptor can be called directly by its method name. For example,
> > > d.__get__(obj).
> > >
> > > Alternatively, it is more common for a descriptor to be invoked
> > > automatically upon attribute access. For example, obj.d looks up d in
> > > the dictionary of obj. If d defines the method __get__, then
> > > d.__get__(obj) is invoked according to the precedence rules listed
> > > below.
> > >
> > > The details of invocation depend on whether obj is an object or a
> > > class. Either way, descriptors only work for new style objects and classes.
> > > A class is new style if it is a subclass of object.
> > >
> > > For objects, the machinery is in object.__getattribute__ which
> > > transforms b.x into type(b).__dict__['x'].__get__(b, type(b)). The
> > > implementation works through a precedence chain that gives data descriptors
> > > priority over instance variables, instance variables priority over non-data
> > > descriptors, and assigns lowest priority to __getattr__ if provided.
> > > The full C implementation can be found in PyObject_GenericGetAttr() in
> > > Objects/object.c.
> > >
> > > For classes, the machinery is in type.__getattribute__ which
> > > transforms B.x into B.__dict__['x'].__get__(None, B). In pure Python,
> > > it looks like:
> > >
> > > def __getattribute__(self, key):
> > >
> > >
> > >     "Emulate type_getattro() in Objects/typeobject.c"
> > >     v = object.__getattribute__(self, key)
> > >     if hasattr(v, '__get__'):
> > >        return v.__get__(None, self)
> > >
> > >     return v
> > >
> > > The important points to remember are:
> > >
> > >    - descriptors are invoked by the __getattribute__ method
> > >    - overriding __getattribute__ prevents automatic descriptor
> > >    calls
> > >    - __getattribute__ is only available with new style classes and
> > >    objects
> > >    - object.__getattribute__ and type.__getattribute__ make
> > >    different calls to __get__.
> > >    - data descriptors always override instance dictionaries.
> > >    - non-data descriptors may be overridden by instance
> > >    dictionaries.
> > >
> > > The object returned by super() also has a custom __getattribute__method for invoking descriptors. The call super(B,
> > > obj).m() searches obj.__class__.__mro__ for the base class A immediately
> > > following B and then returns A.__dict__['m'].__get__(obj, A). If not a
> > > descriptor, m is returned unchanged. If not in the dictionary, mreverts to a search using
> > > object.__getattribute__.
> > >
> > > Note, in Python 2.2, super(B, obj).m() would only invoke __get__ if mwas a data descriptor. In Python
> > > 2.3, non-data descriptors also get invoked unless an old-style class
> > > is involved. The implementation details are in super_getattro() in
> > > Objects/typeobject.c and a pure Python equivalent can be found in Guido's
> > > Tutorial <http://www.python.org/2.2.3/descrintro.html#cooperation>.
> > >
> > > The details above show that the mechanism for descriptors is embedded
> > > in the __getattribute__() methods for object, type, and super. Classes
> > > inherit this machinery when they derive from object or if they have a
> > > meta-class providing similar functionality. Likewise, classes can turn-off
> > > descriptor invocation by overriding __getattribute__().
> > >  Descriptor Example<http://users.rcn.com/python/download/Descriptor.htm#id5>
> > >
> > > The following code creates a class whose objects are data descriptors
> > > which print a message for each get or set. Overriding __getattribute__is alternate approach that could do this for every attribute. However, this
> > > descriptor is useful for monitoring just a few chosen attributes:
> > >
> > > class RevealAccess(object):
> > >     """A data descriptor that sets and returns values
> > >        normally and prints a message logging their access.
> > >     """
> > >
> > >
> > >     def __init__(self, initval=None, name='var'):
> > >         self.val = initval
> > >         self.name = name
> > >
> > >
> > >
> > >     def __get__(self, obj, objtype):
> > >         print 'Retrieving',
> > > self.name
> > >         return self.val
> > >
> > >
> > >     def __set__(self, obj, val):
> > >         print 'Updating' ,
> > > self.name
> > >         self.val = val
> > >
> > > >>> class MyClass(object):
> > >
> > >     x = RevealAccess(10, 'var "x"')
> > >     y = 5
> > >
> > > >>> m = MyClass()
> > > >>> m.x
> > > Retrieving var "x"
> > >
> > > 10
> > > >>> m.x = 20
> > > Updating var "x"
> > >
> > >
> > > >>> m.x
> > > Retrieving var "x"
> > > 20
> > > >>> m.y
> > > 5
> > >
> > > The protocol is simple and offers exciting possibilities. Several use
> > > cases are so common that they have been packaged into individual function
> > > calls. Properties, bound and unbound methods, static methods, and class
> > > methods are all based on the descriptor protocol.
> > > --
> > > It's a long journey to go!
> > >
> >
> > _______________________________________________
> > python-chinese
> > Post: send python-chinese在lists.python.cn
> > Subscribe: send subscribe to python-chinese-request在lists.python.cn
> > Unsubscribe: send unsubscribe to
> > python-chinese-request在lists.python.cn
> > Detail Info: http://python.cn/mailman/listinfo/python-chinese
> >
>
> Ä㻹ÐèÒªºÜ×ÐϸµØ¿´ÏÂÕâ¸ö£º attribute²éÕÒ²ßÂÔ<http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#id822546>
> ÁíÍâÒ²ÏòÄãÍƼöÏÂÎÒÕâƪblog£ºÀí½â python µÄ method ºÍ function ¼æ̸ descriptor
> <http://codeplayer.blogspot.com/2006/12/python-method-function-descriptor.html>
> ;-)
>
> --
> http://codeplayer.blogspot.com/
> _______________________________________________
> python-chinese
> Post: send python-chinese在lists.python.cn
> Subscribe: send subscribe to python-chinese-request在lists.python.cn
> Unsubscribe: send unsubscribe to  python-chinese-request在lists.python.cn
> Detail Info: http://python.cn/mailman/listinfo/python-chinese
>



-- 
It's a long journey to go!
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20070114/8e67a6c0/attachment.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2025

    京ICP备05028076号