[Tutor] like setattr but for methods...

Gonçalo Rodrigues op73418@mail.telepac.pt
Sat May 24 07:19:01 2003


----- Original Message -----
From: "ali mangaliag" <rmangaliag@slu.edu.ph>
To: <tutor@python.org>
Sent: Saturday, May 24, 2003 10:16 AM
Subject: [Tutor] like setattr but for methods...


> if i have a class, X, and an instance of X called Y...
> i can add attributes to Y in two ways:
>
> a.)
> Y.attr1 = 1
> Y.attr2 = "test"
> Y.attr3 = [1,2,3,4,5]
>
> b.)
> setattr(Y,"attr1",1)
> setattr(Y,"attr2","test")
> setattr(Y,"attr3",[1,2,3,4,5])
>
> is my understanding of this correct???
>

Yes

> my second question is... is there a way for me to define a method like the
> way i did (or anything similar) with the attributes above???
>

I'm not sure I understand your question, but i'll try to answer anyway :-)

functions, methods, etc. are first-class objects in Python. This means you
can do things like

>>> class X(object):
...  pass
...
>>> Y = X()
>>> def ridiculous():
...  return "I am a ridiculous function."
...
>>> Y.ridiculous = ridiculous
>>> Y.ridiculous()
'I am a ridiculous function.'
>>>

Notice though that only the Y instance is ridiculous.

>>> another_Y = X()
>>> another_Y.ridiculous()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: 'X' object has no attribute 'ridiculous'
>>>

To make *all* X instances ridiculous you have to attach the ridiculous
function to the class itself, that is, something like

>>> X.ridiculous = ridiculous

And now you do

>>> another_Y.ridiculous()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: ridiculous() takes no arguments (1 given)

Oi, trouble!! The "problem" is that when Python adds a function attribute to
a class it does some magic in the background. I'm not going to explain the
details, but suffices to say that in practical terms you have to add the
self argument to the ridiculous function - as you do to all the usual
methods!!

>>> def ridiculous(self):
...  return "We are all ridiculous!"
...
>>> X.ridiculous = ridiculous
>>> another_Y.ridiculous()
'We are all ridiculous!'

HTH, with my best regards,
G. Rodrigues