Add a method to an existing class
Bruce Edge
bedge at troikanetworks.com
Wed May 16 13:06:12 EDT 2001
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.
Thanks, Bruce.
More information about the Python-list
mailing list