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

关于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个习题,我按书上敲的,不知道哪里出错了,求指点。


第一次执行getattr是成功的,第二次因为next = room(),所以next不是string了,so...


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

第一次运行是没问题的,但运行完
next = room()后,因为testroom()没有返回值,所以next被赋值为空了,继续下去,getattr(self,next)变成了 getattr(self,None)了

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