Home  >  Q&A  >  body text

关于python getattr()函数使用疑问。

我在创建一个类Game 并创建一个属性start,创建一个实例后执行play()方法,使用getattr函数
获取start属性值,也就是要执行的函数名,运行提示getattr 第二个参数(属性名)必须是str类型,但是我创建实例传入的参数"testroom"就是字符串啊,只不过是赋值给变量next了

class Game(object):

    def __init__(self, start):
        self.start = start
        
    def play(self):
        next = self.start
        while True:
            print "\n----------"
            room = getattr(self, next)
            next = room()
    
    def testroom(self):
        pass
a_game = Game("testroom")
a_game.play()

这是笨办法学Python 上的第42个习题,我按书上敲的,不知道哪里出错了,求指点。

PHPzPHPz2766 days ago566

reply all(2)I'll reply

  • PHPz

    PHPz2017-04-17 17:36:18

    def play(self):
            next = self.start
            while next:  #要指定循环的跳出条件
                print "\n----------"
                room = getattr(self, next)  #第一次可以获取到
                next = room()  #因为testroom()没有返回值,这里next变空了
             
             

    There is no problem when running for the first time, but after running
    next = room(), because testroom() has no return value, next is assigned an empty value. If we continue, getattr(self, next) becomes getattr (self,None)

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 17:36:18

    The first execution of getattr was successful. The second time because of next = room(), next is not a string, so...

    reply
    0
  • Cancelreply