Can print() be reloaded for a user defined class?
r
rt8396 at gmail.com
Sat Sep 19 22:34:19 EDT 2009
On Sep 19, 9:28 pm, Peng Yu <pengyu... at gmail.com> wrote:
> Hi,
>
> I have the following code. The last line does not print the members
> ("x" and "y") of 'my_bin'. I am wondering if there is a way to reload
> the print function for bin, so that the last line print the members of
> 'my_bin'.
>
> Regards,
> Peng
>
> class bin:
> def __init__(self, x, y) :
> self.x = x
> self.y = y
>
> if __name__ == '__main__':
>
> my_bin = bin(1, 2)
> print my_bin
use the __str__ and or __repr__ methods
> class Bin:
> def __init__(self, x, y) :
> self.x = x
> self.y = y
def __str__(self):
return 'Bin(%s, %s)' %(self.x, self.y)
__repr__ = __str__
Please use an initial capital letter when defining a class, this is
the accepted way in many languages!!!
More information about the Python-list
mailing list