Simple descriptor

suggest change

There are two different types of descriptors. Data descriptors are defined as objects that define both a __get__() and a __set__() method, whereas non-data descriptors only define a __get__() method. This distinction is important when considering overrides and the namespace of an instance’s dictionary. If a data descriptor and an entry in an instance’s dictionary share the same name, the data descriptor will take precedence. However, if instead a non-data descriptor and an entry in an instance’s dictionary share the same name, the instance dictionary’s entry will take 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.

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

An implemented example:

class DescPrinter(object):
    """A data descriptor that logs activity."""
    _val = 7
    
    def __get__(self, obj, objtype=None):
        print('Getting ...')
        return self._val

    def __set__(self, obj, val):
        print('Setting', val)
        self._val = val
    
    def __delete__(self, obj):
        print('Deleting ...')
        del self._val
class Foo():
    x = DescPrinter()       

i = Foo()
i.x
# Getting ...
# 7

i.x = 100
# Setting 100
i.x
# Getting ...
# 100

del i.x
# Deleting ...
i.x
# Getting ...
# 7

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Descriptor:
* Simple descriptor

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
99 Descriptor
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve