Class methods read-only by default?
Piet van Oostrum
piet at cs.uu.nl
Fri Apr 3 18:52:06 EDT 2009
>>>>> "Emanuele D'Arrigo" <manu3d at gmail.com> (ED) wrote:
>ED> Hi Everybody!
>ED> I just tried this:
>>>>> class C(object):
>ED> ... def method(self):
>ED> ... pass
>ED> ...
>>>>> c = C()
>>>>> delattr(c, "method")
>ED> Traceback (most recent call last):
>ED> File "<stdin>", line 1, in <module>
>ED> AttributeError: 'C' object attribute 'method' is read-only
>ED> How come? Who told the class to make the method read-only? I didn't!
Methods in a class are done with the descriptor protocol. All access to
the method through an instance is executed via the descriptor. The
delete calls the __delete__ method of the descriptor which isn't
implemented for functions. See
http://docs.python.org/reference/datamodel.html?highlight=descriptor#implementing-descriptors
(Actually, IIRC, the function object is its own descriptor)
>>> class C(object):
... def method(self):
... pass
...
>>> c=C()
>>> C.__dict__['method']
<function method at 0xd2330>
>>> C.__dict__['method'].__get__
<method-wrapper '__get__' of function object at 0xd2330>
>>> C.__dict__['method'].__delete__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute '__delete__'
>>>
--
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org
More information about the Python-list
mailing list