0
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 %s. What is thine class? " % self.herodict['Name'],
            "AskWeapon": "A %s ? What shalt thy weapon be? " % self.herodict['Class'],
        }

    def setHeroDict(self, textkey, herokey):
        n = raw_input(self.herotext[textkey])
        self.herodict[herokey] = n
        print self.herodict[herokey]



h = hero("Tommy", "Mage", "Staff")
h.setHeroDict("Welcome", "Name")
h.setHeroDict("AskClass", "Class")

よし、ここで一度これを尋ねたところ、賢い人がラムダを使ってみるように言った。私はそれを試してみましたが、うまくいきました。すごい!ただし、ここでの私の質問は少し異なります。私がそこで述べたように、私はこれにかなり慣れていないので、私の知識には埋めようとしている多くの穴があります. 基本的に..ラムダを使用せずにこれをより適切に行うにはどうすればよいですか(または、通常、これにラムダを使用しますか?)

私がやろうとしていること:

  1. いくつかのデフォルトが添付されたいくつかの変数を持つヒーロークラスを用意します。
  2. herotext次に、myを使用して値の 1 つを使用して質問できる定義を使用したいと考えています。
  3. 次に、ユーザーが質問に答えると、その定義が進み、適切な値が変更されますherodict

渡されようとしている問題: 私のherotext中には、それ自体が のキーを指す値がありますherodict。リンクで説明されているように、これは、ユーザーが入力を提供する前にherodictデフォルト値に初期化されるためです。herotextしたがって、「AskClass」self.herodict['Name']値の新しいユーザー入力名の代わりに、デフォルト (この場合は Tommy) の名前が出力されます。

これを修正するにはどうすればよいですか? 別のファイルなどを作成する必要があるかどうかは気にしません。この種のことを行うためのより論理的な方法を知りたいだけですか? 私は一日中これにこだわっていて、私の心は友達です。多くの人にとっては簡単なことかもしれませんが、知識を共有していただければ幸いです。

ありがとう

4

2 に答える 2

1

どうぞ。これは非常にクリーンな方法です。まもなく、私はあなたのクラスの私のバージョンを投稿します。:-) (まあ、そうするつもりでしたが、これはすでにかなり多忙です..)

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")

説明:

「フォーマット」は、% が行うことを行う新しいものです。上記の行でも % メソッドを使用できます。これら 2 つは同等です。

"Hello, {foo}".format(**{'foo': 'bar'})
"Hello, %(foo)s!" % {'foo': 'bar'}

いずれにせよ、アイデアはテンプレート文字列を上書きしないようにすることです。文字列テンプレートを作成していたときは、それらを使用してから、値を変数に割り当てていました。

5 * 10 が常に 50 に置き換えられるように、'meow%s' % 'meow!' 常に「ニャーニャー!」に置き換えられます。5、10、および両方の鳴き声は、他の場所で参照されていない限り、自動的にガベージ コレクションされます。

>>> print 5 * 10
50
>>> # the five, ten, and the 50 are now gone.
>>> template = "meow {}"
>>> template.format('splat!')
'meow splat!'
>>> # 'splat!' and 'meow splat!' are both gone, but your template still exists.
>>> template
'meow {}'
>>> template = template % 'hiss!'  # this evaluates to "template = 'meow hiss!'"
>>> template  # our template is now gone, replaced with 'meow hiss!' 
'meow hiss!'

..そのため、テンプレートを変数に保存し、テンプレートを使用して作成した文字列を使用してそれらを「保存」しないでください。

于 2013-06-01T02:02:38.880 に答える