python2.7 - python 中 getattr 使用 为什么这样报错?
巴扎黑
巴扎黑 2017-04-17 14:52:41
0
2
868
#-*-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 上就又不报错了

巴扎黑
巴扎黑

reply all(2)
巴扎黑

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.

Ty80

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!