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