gpt4 book ai didi

python - 使用 getattr() 而不返回,出现以下错误 : getattr(): attribute name must be string

转载 作者:行者123 更新时间:2023-12-01 04:43:27 24 4
gpt4 key购买 nike

Python版本
python -VPython 2.7.9::Anaconda 2.0.1 (x86_64)

如果没有返回或退出,则会出现错误:

第 16 行,正在播放
房间 = getattr(自身, 下一个)
类型错误:getattr():属性名称必须是字符串

但是在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()

最佳答案

您在 while 循环中设置了 next = room() ,该循环在第一次迭代后设置为 None ,如果您想转到 al 中的方法,则需要返回 self.play 。

我想你也想调用死亡并抄送:

 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 作为变量名,因为它会隐藏内置函数。

关于python - 使用 getattr() 而不返回,出现以下错误 : getattr(): attribute name must be string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30025824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com