Class methods read-only by default?

andrew cooke andrew at acooke.org
Thu Apr 2 09:30:46 EDT 2009


Emanuele D'Arrigo wrote:
> Hi Everybody!
>
> I just tried this:
>
>>>> class C(object):
> ...    def method(self):
> ...        pass
> ...
>>>> c = C()
>>>> delattr(c, "method")
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'C' object attribute 'method' is read-only
>
> How come? Who told the class to make the method read-only? I didn't!

i'm just guessing, but i suspect this is because of how it's implemented. 
class methods don't exist "in" the instance.  instead, they exist in the
class (which is itself an "object", hence metaclasses etc), and the
instance forwards them to the class for evaluation (if the term vtable
makes any sense to you then the vtable for class methods is owned by the
class, not the instance).

so you may be able to delete the method from the class, but then it will
affect all instances.  you can't delete it from one instance because it's
not in that instance.

as i said, just a guess, based on vague ideas about how python works.

andrew





More information about the Python-list mailing list