python版本
python -V
Python 2.7.9 :: Anaconda 2.0.1(x86_64)
如果没有返回或退出,则会收到错误:
line 16, in play
room = getattr(self, next)
TypeError: getattr(): attribute name must be string
但在ideone.com在线可以
#-*-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()
#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()
答案 0 :(得分:2)
在第一次迭代后设置在“无”旁边的while循环中设置next = room()
,如果要从al转到方法,则需要返回self.play。
我想你也想叫死亡和cccl:
def al(self):
print "this is al"
action = raw_input("> ")
if action == '1':
return self.death()
elif action == '2':
return self.cccl()
return self.play()
我会避免使用next
作为隐藏内置函数的变量名。