关于python getattr()函数使用疑问。
PHPz
PHPz 2017-04-17 17:34:18
0
2
557

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

PHPz
PHPz

学习是最好的投资!

reply all(2)
PHPzhong
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)

左手右手慢动作

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

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!