Class methods read-only by default?
andrew at acooke.org
Thu Apr 2 15:30:46 CEST 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.
More information about the Python-list