Python getattr报TypeError错误,getattrtypeerror,#-*-coding:u
Python getattr报TypeError错误,getattrtypeerror,#-*-coding:u
#-*-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 上就又不报错了
正确的写法为room = getattr(self, 'next').
你可以认为getattr向对象传递了一条名字叫做'next'的短信, 请求'next'的内容. 既然是短信, 那必须是字符串啦.
getattr 第二个参数必须为 str,而代码里面 next = room() 应该是这个 room 返回了一个非 str 的东西。说起来 room 是个什么鬼?代码片段里面根本没出现过。
编橙之家文章,
相关内容
- Python当前目录有同名模块请问如何导入内置socket模块,
- 请问django csrf文档中下面句话应该如何理解,djangocsrf
- 这段python django源码不处理PUT方法带表单什么原因,py
- 怎么处理Python解析服务器json格式数据,pythonjson,RT,服
- django正确使用csrf求高手指点,djangocsrf,每次要做csrf保护
- 有脚本版本好自动更新python方法吗?,有脚python,经常看
- 新手对python列表赋值问题的不解,python列表赋值不解
- python语言中两个不同模块可以互相导入吗?,python语言
- python 钩子如何实现分析流程操作,python钩子,在一个项
- Python多线程进度条progressbar没能达到预期,pythonprogres
评论关闭