__str__ for each function in a class

Terry Reedy tjreedy at udel.edu
Wed May 19 11:02:38 EDT 2010


On 5/19/2010 1:14 AM, Vincent Davis wrote:
>
> I am sure this is easy but I am not sure how to do it and google was
> failing me.
> Lets say I have a class() with an def x() and def y() and I want
> print(class.x) and (class.y) to have custom prints (__str__) how do I do
> this
> For example
> class C(object):
>      def __init__(self, new):
>          self.letter = dict(a=1,b=2,c=3, amin=np.amin)
>          self.new = new
>          self._x = None
>          self._Y = None
>
>      @property
>      def x(self):
> """I'm the 'x' property."""
>          self._x = self.new
>          return self._x
>
>      @property
>      def y(self):
> """I'm the 'x' property."""
>          self._y = self.new*-1
>          return self._y
>
> .......
>  >>> print(class.x)

'class' is a keyword, so this is a syntax error.
Did you mean C.x?

> ****x****

In any case, the printing of an object ob is controlled by 
type(ob).__str__ and type(ob).__repr__, so you can only control the 
printing of instances of custom type. You cannot replace methods of 
builtin classes.

Terry Jan Reedy




More information about the Python-list mailing list