Print String

Peter Otten __peter__ at web.de
Tue Jun 1 21:32:22 CEST 2004


Balaji wrote:

> I have written a method which prints the prefix notation of any
> expression.
> 
> here is the method...

The convention is to call it "method" only if it is part of a class, so what
you show is a "function".

> def PrintPrefix(expr):
> if expr.__class__==E:

Explicit class checks are a bad idea. I'd rather let the class decide how it
wants to print or convert an instance to string - i. e. I would prefer
methods over a function to implement this feature.

> print expr.operator,
>                         PrintPrefix(expr.left),
>                         PrintPrefix(expr.right),
>                  else:
>                          print expr,
> 
> Now if i pass an expression to it like e1=x+y+z:
> 
> I call it by passing PrintPrefix(e1):
> The output is ++xyz
> 
> now i want to store this in a string...

Below is a minimal example that uses __str__() (the method that is
implicitely called by the str() function) to produce infix notation and
__repr__() (corresponding to repr()) for prefix notation. Just say

print repr(e) 

to print in prefix notation and

s = repr(e)

to store it as a string.

class Base(object):
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return self.name
    __repr__ = __str__
    def __add__(self, other):
        return Expression(Operator("+"), self, other)

class Operator(Base):
    pass

class Variable(Base):
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return self.name

class Expression(Base): 
    def __init__(self, operator, left, right):
        self.operator = operator
        self.left = left
        self.right = right
    def __str__(self):
        """ infix """
        return "%s%s%s" % (self.left, self.operator, self.right)
    def __repr__(self):
        """ prefix """
        return "%r%r%r" % (self.operator, self.left, self.right)

x = Variable("x")
y = Variable("y")
z = Variable("z")
e = x + y + z
print repr(e)
print str(e)


Peter




More information about the Python-list mailing list