Add a method to an existing class

Remco Gerlich scarblac at pino.selwerd.nl
Wed May 16 23:38:16 CEST 2001


Bruce Edge <bedge at troikanetworks.com> wrote in comp.lang.python:
> 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.
> 
> eg:
> 
> >>> class xx:
> ...	def __init__(self):
> ...		self.i = 99
> 
> >>> x = xx()
> 
> Now, I want to add __repr__ to class xx. I tried the following:
> 
> >>> def str(self):
> ...  return "%d" % self.i
> 
> >>> xx.__dict__['__repr__']=str
> >>> x=xx()
> >>> x
> 99
>
> It works, but I'm wondering if this is the right way.

Simply

xx.__repr__ = str

seems easier to me.

Note that calling your function 'str' is a bit unfortunate, since that masks
the builtin function str().

You don't even need any extra name in this case, a lambda is enough:

xx.__repr__ = lambda self: "%d" % self.i

-- 
Remco Gerlich



More information about the Python-list mailing list