首页 > python 中 getattr 使用 为什么这样报错?

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 上就又不报错了


正确的写法为room = getattr(self, 'next').

你可以认为getattr向对象传递了一条名字叫做'next'的短信, 请求'next'的内容. 既然是短信, 那必须是字符串啦.


getattr 第二个参数必须为 str,而代码里面 next = room() 应该是这个 room 返回了一个非 str 的东西。说起来 room 是个什么鬼?代码片段里面根本没出现过。

【热门文章】
【热门文章】