Add a method to an existing class

Emile van Sebille emile at fenx.com
Wed May 16 14:59:41 EDT 2001


If I understand correctly, this creates an instance method.

>>> class myclass:
 val = 5


>>> inst = myclass()
>>> def showval(self): return str(self.val)

>>> inst.__repr__ = new.instancemethod(showval, inst, myclass)
>>> inst
5

--

Emile van Sebille
emile at fenx.com

---------
"Pete Shinners" <pete at visionart.com> wrote in message
news:9duhb2$q8b$1 at news.unitel.co.kr...
> "Bruce Edge" <bedge at troikanetworks.com> wrote
> > I have some idl generated classes. I'd like to add a __repr__ method to
> > control default output representation.
> > So, my question is, how does one add a method to an existing class when
> > you don't have control of the class definition.
>
> hello bruce, this likely isn't the cleanest way to do this, but
> it's the best i've been able to come up with. you can define a
> new function (that takes self for the first argument) and assign
> that method to the class of your instance.
>
> >>> class myclass:
> ...     val = 5
> ...
> >>> inst = myclass()
> >>> print inst
> <__main__.myclass instance at 007F442C>
> >>> def showval(self): return str(self.val)
> ...
> >>> myclass.__repr__ = showval
> >>> print inst
> 5
>
> note that this will change the "repr" for all instances of the
> class, but that should be fine for a __repr__ type of function.
>
> sadly, trying to assign the function to be a method of the instance
> doesn't work. the function doesn't really become a "method" it
> just remains a function, and it does get the "self" argument
> filled when called. i would really like to know if there is a
> clean way to actually make that function a full method?
>
>





More information about the Python-list mailing list