使用getattr()而不返回,出现以下错误:getattr():属性名必须是字符串

时间:2015-05-04 08:34:24

标签: python return getattr

python版本
python -V Python 2.7.9 :: Anaconda 2.0.1(x86_64)

如果没有返回或退出,则会收到错误:

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

但在ideone.com在线可以

#-*-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() 
        #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()

1 个答案:

答案 0 :(得分:2)

在第一次迭代后设置在“无”旁边的while循环中设置next = room(),如果要从al转到方法,则需要返回self.play。

我想你也想叫死亡和cccl:

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

我会避免使用next作为隐藏内置函数的变量名。