[Tutor] setattr and classes

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Mar 18 00:07:47 EST 2004



On Wed, 17 Mar 2004, Luiz Siqueira Neto wrote:

> Only a class of object "x" can have the __setattr__ of "x"?


Hi Luiz,

Let me make sure I understand the question: are you asking if it's
possible to define the __setattr__ of individual instances? If not, I have
to admit that I'm confused.  Can you rephrase your question?  A concrete
example may help make things more clear for me.


But if so, then yes, it's possible to customize the methods of individual
instances in Python.  Here's an example:

###
>>> class Foo:
...     def mymethod(self):
...         print "I am a method"
...
>>> f = Foo()
>>> f.mymethod()
I am a method
###


Ok, so here's a toy class.  It's possible to redefine 'mymethod()' here
specifically just for one instance:

###
>>> def some_function():
...     print "huh?"
...
>>> another_f.mymethod = some_function
>>> another_f.mymethod()
huh?
>>> f.mymethod()
I am a method
###

This doesn't quite work, since some_function isn't taking in a 'self'.
But it's close, and it shows that we can jerry-rig a function to an
instance.  But it's also possible to attach arbitrary methods that are
also 'self' aware.


A working way to do this is with a function called new.instancemethod():

###
>>> f = Foo()
>>> def talk(self):
...     print "I, a", self, "am self aware"
...
>>> import new
>>> f.talk = new.instancemethod(talk, f, Foo)
>>> f.talk()
I, a <__main__.Foo instance at 0x41ee0> am self aware
###

So this 'f' instance is a little bit more individual than the rest of its
kin: it's the only Foo with a talk() method.


That being said, it may not be a good idea to do this kind of dynamic
redefinition.  It becomes more messy to figure out what method an instance
has: classes are supposed to guarantee that certain methods are attached
to a class.  But it's interesting to know we can do this, even if we never
do it in practice.


Hope this helps!




More information about the Tutor mailing list