【问题标题】:Why is the dictionary automatically printing without me telling it to?为什么字典会自动打印而我没有告诉它?
【发布时间】:2013-12-18 01:02:22
【问题描述】:

我正在搞乱类和字典,试图了解如何更好地使用它们。我想出的想法是创建一堆类,为某个对象提供一堆不同的描述符,我使用 D&D 中的怪物,然后创建一个包含所有这些怪物的字典,以便我可以使用来自从类中加载描述符的字典。

import dice #a dice module i made
import textwrap

class Goblin(object):
    def __init__(self):
        self.name = 'Goblin'
        self.desc = 'bla bla bla, I'm not going to type the whole thing.'
        self.health = dice.d8.roll(1) + 1

    def describe(self):
        print self.name
        print self.health, 'other random info not in self.desc'
        print textwrap.fill(self.desc, 60)

goblin = Goblin() 所以这是我的班级设置。当我输入 print goblin.describe() 时,一切正常。然后我设置了我的字典:

bestiary = {
    'Goblin': goblin.describe()
    }

我删除了 goblin.describe(),所以没有命令告诉程序打印任何内容,但是当我运行程序时,它运行 goblin.describe() 并显示描述我的地精的文本块。我的问题是它为什么要这样做,有没有办法让它不那样做,所以我可以独立使用 goblin.describe() 或 any_other_monster_I make.describe() 并让它拉出描述?

我知道可能有更简单的方法可以做到这一点,但我只是想弄清楚为什么它会这样做。

【问题讨论】:

    标签: python class dictionary


    【解决方案1】:

    你实际上是在评估 describe here(调用它)

    bestiary = {
        'Goblin': goblin.describe()
    }
    

    你可以尝试返回字符串而不是打印它:

    import dice #a dice module i made
    import textwrap
    
    class Goblin(object):
        def __init__(self):
            self.name = 'Goblin'
            self.desc = 'bla bla bla, I''m not going to type the whole thing.'
            self.health = dice.d8.roll(1) + 1
    
    def describe(self):
        return self.name + " " + self.health + " " + 'other random info not in self.desc ' \
               + 'other random info not in self.desc ' + textwrap.fill(self.desc, 60)
    
    
    goblin = Goblin()
    
    bestiary = {
        'Goblin': goblin.describe()
    }
    

    【讨论】:

      【解决方案2】:

      基于“当我输入 print goblin.describe() 时一切正常。”我想你想要这样的东西:

      def describe(self):
          result = ""
          result += self.name
          result += str(self.health) + ' other random info not in self.desc'
          result += textwrap.fill(self.desc, 60)
          return result
      

      即从 describe() 返回描述,不要在方法内打印。

      【讨论】:

      • 所以即使 goblin.describe() 在字典中,它仍然会像不在字典中一样运行?
      • bestiary = {'Goblin': goblin.describe()} 意思是:执行 goblin.describe() 并将结果放在字典 bestiary 中的键 'Goblin' 下。或者,您可以将函数本身(不是其执行的结果)放入字典中,只需删除括号: bestiary = {'Goblin': goblin.describe}
      • 一般来说,str.join 是一个字符串的可迭代对象,而不是使用+= 来构造结果。
      • mgilson,我同意。这就是我写“类似这样的东西”的原因。这个问题并不重要,我想尽可能简单地提出这个想法。
      • @Hitstein 如果函数打印,它将始终打印。调用函数的位置/时间无关紧要。字典不会将标准排除在外。有没有一种语言是你来自哪里的函数可以有条件地打印的?
      【解决方案3】:

      我不确定我是否完全按照您要执行的操作。我真的不明白你所说的“deleted goblin.describe()”是什么意思。你的意思是你从字典中删除了它,或者你从类中删除了那个方法?在任何一种情况下,也许有一些缓存?删除工作目录中的所有 .pyc 文件,然后重试。

      或者您可能正在尝试将该方法添加到字典中,以便您可以稍后调用 describe?您可以只添加方法而不是调用它(请记住,在 python 中,包括方法在内的所有内容都是对象)。因此,您可以完美地做到:

      goblin = Goblin()
      bestiary = { 'Goblin' : goblin.describe }
      # and later call 'describe' as follows
      bestiary['Goblin']()
      
      # though personally I'd opt for the following which is more legible
      goblin = Goblin()
      bestiary = { 'Goblin' : goblin }
      bestiary['Goblin'].describe()
      

      【讨论】:

        【解决方案4】:

        我知道可能有更简单的方法可以做到这一点,但我只是想弄清楚为什么会这样做。

        采取这样的措施:

        def bla():
           print("bla")
        
        def alb():
           return("alb")
        
        bbb = bla()
        aaa = alb() #this could be anthing not just "aaa= alb()" it could be something like thing_dict = {'thing': alb() }
        

        bla 函数将打印“bla”。打印是一种简单的说法:“它进入标准输出,这很可能是你的控制台”这个打印发生在bla 返回之前,所以它只是被打印然后返回none(因为你没有告诉它返回任何东西)(所有功能都返回无,除非另有说明)

        bla()可以改写为

        def bla():
            print("bla")
            return None
        

        它会做同样的事情。

        alb 函数返回“alb”,因为您明确告诉它这样做。

        如果您执行type(bbb),您将得到NoneType,因为bla() 没有返回任何内容

        如果您执行type(aaa),您将得到str,因为alb() 函数返回“alb”

        如果您执行print(bbb),您将得到None,因为这就是bla() 返回的内容(您没有定义返回,所以它返回了None

        如果您执行print(aaa),您将得到“alb”,因为您告诉alb() 将其返回

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-02-24
          • 1970-01-01
          • 2021-01-18
          • 1970-01-01
          • 2021-05-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多