几段 Python 代码理解面向对象

david85142 2年前
   <p><img src="https://simg.open-open.com/show/ac90ba68292b9d9c82e4b2867f5db885.jpg"></p>    <p> </p>    <h2>目录</h2>    <ol>     <li>定义一个游戏输入,对输入简单解析并做出反应</li>     <li>为游戏对象添加查看状态的方法</li>     <li>为 Goblin 类添加更详细的信息</li>    </ol>    <p> </p>    <h2>正文</h2>    <p> </p>    <h3><strong>1.定义一个游戏输入,对输入简单解析并做出反应</strong></h3>    <p> </p>    <p>源代码:</p>    <p>a-simple-game.py</p>    <pre>  <code class="language-python"># 获取输入并解析出输入对应的动作  def get_input():      command = input(":").split()      verbo_word = command[0]      if verbo_word in verb_dict:          verb = verb_dict[verbo_word]      else:          print("Unknown verb {}".format(verbo_word))          return        if len(command) >= 2:          noun_word = command[1]          print(verb(noun_word))      else:          print(verb("nothing"))    # 具体的动作  def say(noun):      return "You said {}".format(noun)    # 将动词和动作对应起来  verb_dict = {      "say": say,  }    while True:      get_input()</code></pre>    <p> </p>    <p>运行结果:</p>    <p> </p>    <p><img src="https://simg.open-open.com/show/4475ec16d19ecdcd4f4e0301c99f611e.png"></p>    <p> </p>    <p> </p>    <h3><strong>2.为游戏对象添加查看状态的方法</strong></h3>    <p>代码:</p>    <pre>  <code class="language-python">class GameObject:      class_name = ""      desc = ""      objects = {}        def __init__(self, name):          self.name = name          GameObject.objects[self.class_name] = self        def get_desc(self):          return self.class_name + "\n" + self.desc      # 创建一个继承自游戏对象类的哥布林类  class Goblin(GameObject):      class_name = "goblin"      desc = "A foul creature"    goblin = Goblin("Gobbly")    # 具体的动作  def examine(noun):      if noun in GameObject.objects:          return GameObject.objects[noun].get_desc()      else:          return "There is no {} here.".format(noun)</code></pre>    <p> </p>    <p>以上代码创建了一个继承自 <strong>GameObject</strong> 类的 <strong>Goblin</strong> 类,也创建一个新的 <strong>examine</strong> 方法,于是我们添加一个新的 <em>examine</em> 动词进去:</p>    <pre>  <code class="language-python"># 将动词和动作对应起来  verb_dict = {      "say": say,      "examine": examine,  }</code></pre>    <p> </p>    <p>代码和上一个小 <em>demo</em> 合并起来,运行看看:</p>    <p> </p>    <p> </p>    <p><img src="https://simg.open-open.com/show/a8f8e21263766b6f43730fac29459474.png"></p>    <h3>3.为 Goblin 类添加更详细的信息,并添加 hit 动作,让你可以打 Goblin(有点意思了~)</h3>    <p> </p>    <p>代码(只列出修改过的与添加的):</p>    <pre>  <code class="language-python">class Goblin(GameObject):      def __init__(self, name):          self.class_name = "goblin"          self.health = 3          self._desc = "A foul creature"          super().__init__(name)        @property      def desc(self):          if self.health >= 3:              return self._desc          elif self.health == 2:              health_line = "It has a wound on its knee."          elif self.health == 1:              health_line = "Its left arm has been cut off."          elif self.health <= 0:              health_line = "It is dead."          return self._desc + "\n" + health_line        @desc.setter      def desc(self, value):          self._desc = value    def hit(noun):      if noun in GameObject.objects:          thing = GameObject.objects[noun]          if type(thing) == Goblin:              thing.health -= 1              if thing.health <= 0:                  msg = "You killed the goblin!"              else:                  msg = "You hit the {}".format(thing.class_name)          else:              msg = "I'm not strong enough, I can only hit goblin."      else:          msg = "There is no {} here.".format(noun)      return msg    # 将动词和动作对应起来  verb_dict = {      "say": say,      "examine": examine,      "hit": hit,  }</code></pre>    <p> </p>    <p>运行:</p>    <p> </p>    <p><img src="https://simg.open-open.com/show/236cecdbab853df59b31dac9ad4866df.png"></p>    <p>这里有 <a href="/misc/goto?guid=4959751271140875047" rel="nofollow,noindex"> 完整代码 </a> ,是不是简单又有趣~点个赞吧~</p>    <p> </p>    <p>来自:https://zhuanlan.zhihu.com/p/28409354</p>    <p> </p>