[Tutor] designing POOP

Kent Johnson kent37 at tds.net
Sat Feb 9 19:58:37 CET 2008


Alan Gauld wrote:

> class Explorer(object):
>     fmtStr = """
> My name is %s
> and I have wealth of $%s and 
> strength of %s"""
> 
>     # other code here    
> 
>     def describe(withText=False)
>          values = (self.name, self.wealth, self.strenth)
>          if not withText:
>               return values
>          else
>               return fmtStr % values

Should be self.fmtStr or Explorer.fmtStr

> We can then call that as
> 
> e = Explorer()
> ....
> e.describe(withText=True)   # gets the long version
> 
> or
> 
> print """
> You are an explorer whose name is %s, 
> You have wealth of %s and strength of %s
> """ % e.describe()  # uses tuple result

Um, yuck. A function that returns either a string or a tuple depending 
on its parameter? How about

class Explorer:
   ...
   def __str__(self):
     fmtStr = """
My name is %s
and I have wealth of $%s and
strength of %s"""
     return fmtStr % self.values()

   def values(self):
     return (self.name, self.wealth, self.strenth)

Or get rid of values() entirely and just refer to the attributes 
directly - what if you want to print the values in a different order?

Kent


More information about the Tutor mailing list