Home  >  Q&A  >  body text

python2.7 - python 中 getattr 使用 为什么这样报错?

#-*-coding:utf-8-*-
from sys import exit 


class newgame(object):
    def __init__(self, start): 
        self.start = start
        #self.cccl()

    def play(self):
        next = self.start

        while True:
            print "\n--------"
            print next
            room = getattr(self, next)
            next = room()

    def death(self):
        print "this is death"
        exit(-1)


    def cccl(self):
        print "this is bbbb"
        #return self.al() 如果加上return 或者 exit 就成功不加则报错
        #exit(1) 

    def al(self):
        print "this is al"
        action = raw_input("> ")
        if action == '1':
                return "death"
        elif action == '2':
                return "cccl"

ngame = newgame("al")
ngame.play()

line 17, in play
room = getattr(self, next)
TypeError: getattr(): attribute name must be string

请问这是为什么呢?
pyenv version
anaconda-2.0.1 (set by /usr/local/opt/pyenv/version)

但是放到 ideone.com 上就又不报错了

巴扎黑巴扎黑2766 days ago892

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 14:54:41

    getattr The second parameter must be str, and next = room() in the code should be this. room returns something other than str. Speaking of which, what the hell is room? It doesn't appear at all in the code snippet.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:54:41

    The correct way to write

    is room = getattr(self, 'next').

    You can think of getattr as passing a text message named 'next' to the object, requesting the content of 'next'. Since it is a text message, it must be a string.

    reply
    0
  • Cancelreply