poone
poone

Reputation: 44

Use getattr() without return , following error: getattr(): attribute name must be string

python version
python -V Python 2.7.9 :: Anaconda 2.0.1 (x86_64)

Without return or exit it gets the error:

line 16, in play room = getattr(self, next) TypeError: getattr(): attribute name must be string

but at ideone.com online its ok

#-*-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()

Upvotes: 1

Views: 960

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180441

You set next = room() in the while loop which sets next to None after the first iteration, you need to return self.play if you want to go to the method from al.

I imagine you also want to call death and 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()

I would avoid using next as a variable name which shadows the builtin function.

Upvotes: 2

Related Questions