为什么我不告诉字典就自动打印出来了?

2024-03-29 09:49:07 发布

您现在位置:Python中文网/ 问答频道 /正文

为了更好地使用它们,我在课堂和字典里混日子。我的想法是创建一组类,为某个对象提供一组不同的描述符,我使用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() 这就是我的课程设置。当我印出来的时候地精。描述一下()一切正常。然后我建立了我的字典:

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

我删除了地精。描述一下(),因此没有命令告诉程序打印任何内容,但当我运行程序时,它会运行地精。描述一下()并显示描述我的地精的文本块。我的问题是,它为什么要这样做,有没有办法让它不这样做,这样我就可以独立使用地精。描述一下()或任何其他怪物制造、描述()并让它调出描述?你知道吗

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


Tags: nameimportself字典defnotdicedesc
3条回答

我不确定我是否完全明白你的意思。我真的不明白你说的“删除”是什么意思地精。描述一下()". 你的意思是从dict中删除了它,还是从类中删除了那个方法?不管是哪种情况,也许是一些缓存?请删除工作目录中的所有.pyc文件,然后重试。你知道吗

或者您正试图将该方法添加到字典中,以便稍后调用descripe?您可以只添加方法,而不是调用它(记住,在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()

基于“当我出版时”地精。描述一下()一切正常。“我想你想要这样的东西:

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

即从descripe()返回描述,不要在方法内部打印。你知道吗

实际上你在这里(称之为)

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()
}

相关问题 更多 >