Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here you go. This is a pretty clean method to do it. Shortly, I'll post my version of your class. :-) (well, I was going to, but this is already pretty prolix..)</p> <pre><code>class hero(): def __init__(self, name="Jimmy", prof="Warrior", weapon="Sword"): """Constructor for hero""" self.name = name self.prof = prof self.weapon = weapon self.herodict = { "Name": self.name, "Class": self.prof, "Weapon": self.weapon } self.herotext = { "Welcome": "Greetings, hero. What is thine name? ", "AskClass": "A fine name {Name}. What is thine class? ", "AskWeapon": "A {Class}? What shalt thy weapon be? ", } def setHeroDict(self, textkey, herokey): n = raw_input(self.herotext[textkey].format(**self.herodict)) self.herodict[herokey] = n print self.herodict[herokey] h = hero("Tommy", "Mage", "Staff") h.setHeroDict("Welcome", "Name") h.setHeroDict("AskClass", "Class") </code></pre> <p>Explanation:</p> <p>'format' is just a newer thing that does about what % does. The line above could have used the % method too. These two are equivalent:</p> <pre><code>"Hello, {foo}".format(**{'foo': 'bar'}) "Hello, %(foo)s!" % {'foo': 'bar'} </code></pre> <p>Either way, the idea is to avoid overwriting your template string. At the time you were creating your string templates, you were using them, then assigning the value to a variable. </p> <p>Just as 5 * 10 always gets replaced with 50, 'meow%s' % 'meow!' is always replaced with "meow meow!". The five, ten, and both meows are automatically garbage collected, unless there's a reference to them elsewhere.</p> <pre><code>&gt;&gt;&gt; print 5 * 10 50 &gt;&gt;&gt; # the five, ten, and the 50 are now gone. &gt;&gt;&gt; template = "meow {}" &gt;&gt;&gt; template.format('splat!') 'meow splat!' &gt;&gt;&gt; # 'splat!' and 'meow splat!' are both gone, but your template still exists. &gt;&gt;&gt; template 'meow {}' &gt;&gt;&gt; template = template % 'hiss!' # this evaluates to "template = 'meow hiss!'" &gt;&gt;&gt; template # our template is now gone, replaced with 'meow hiss!' 'meow hiss!' </code></pre> <p>..so, store your template in a variable, and and don't 'save over' them with the strings you create using them, unless you're done with the template and it makes sense to do so.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload