我在弄乱类和字典,试图了解如何更好地使用它们。我想到的想法是创建一堆类,为某个对象提供一堆不同的描述符,我使用了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()
因此,这是我的课程设置。当我放入打印文件goblin.describe()时,一切正常。然后我设置了字典:
bestiary = {
'Goblin': goblin.describe()
}
我删除了goblin.describe(),所以没有命令告诉程序打印任何内容,但是当我运行程序时,它将运行goblin.describe()并显示描述我的哥布林的文本块。我的问题是为什么要这样做,有没有办法使它不这样做,所以我可以独立使用goblin.describe()或any_other_monster_I make.describe()并进行描述?
我知道可能有更简单的方法可以做到这一点,但我只是想弄清楚为什么要这样做。
最佳答案
好吧,您实际上正在评估在这里描述(称为它)
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()
}
关于python - 为什么词典在不通知我的情况下自动打印?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20647820/