Class methods read-only by default?

  • Thread starter Emanuele D'Arrigo
  • Start date
E

Emanuele D'Arrigo

Hi Everybody!

I just tried this:
.... def method(self):
.... pass
....
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!

Manu
 
E

Emanuele D'Arrigo

Thank you both, Steven and Andrew, for the insightful explanation. I
shall keep it in mind when thinking about classes methods and
instances. Thank you again.

Manu
 
P

Piet van Oostrum

Emanuele D'Arrigo said:
ED> Hi Everybody!
ED> I just tried this:
ED> ... def method(self):
ED> ... pass
ED> ...
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)
.... def method(self):
.... pass
....
c=C()
C.__dict__['method']
C.__dict__['method'].__get__
C.__dict__['method'].__delete__
Traceback (most recent call last):
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,294
Messages
2,571,507
Members
48,193
Latest member
DannyRober

Latest Threads

Top