[Tutor] designing POOP
Alan Gauld
alan.gauld at btinternet.com
Sat Feb 9 19:41:19 CET 2008
> ..., I'd like to have the finished program
> be identical to the procedural program as far as I/O goes.
You could do it but it would be easier to change it a little
because the original games prompts etc betray its internal
structure. You can just get the objects to return their attributes
and use string formatting to insert those in your prompts.
But it might be better to have the objercts return the whole string
including values. Of course you can do that easily with
a default parameter in a method:
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
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
Using this technique you could use exactly the same text as
in the original or create a more OO variant where the objects
all know how to describe themselves.
Alan G.
More information about the Tutor
mailing list