#-*-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() 如果加上return 或者 exit 就成功不加则报错
#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()
line 17, in play
room = getattr(self, next)
TypeError: getattr(): attribute name must be string
请问这是为什么呢?
pyenv version
anaconda-2.0.1 (set by /usr/local/opt/pyenv/version)
但是放到 ideone.com 上就又不报错了
getattr
第二個參數必須為str
,而程式碼裡面next = room()
應該是這個room
回傳了一個非 str 的東西。說起來room
是個什麼鬼?程式碼片段裡面根本沒出現過。正確的寫法為
room = getattr(self, 'next')
.你可以認為
getattr
向對象傳遞了一條名字叫做'next'
的短信, 請求'next'
的內容. 既然是短信, 那必須是字符串啦.