类实例初始化时的NameError

时间:2014-10-20 19:54:11

标签: python

我已经玩了几个星期的脚本并且没有任何问题,但我现在正在尝试创建一个类并遇到问题。

我自己并不完全理解,但是当我尝试创建以下类的实例时,我收到此错误NameError: global name 'instance_status_check' is not defined

我完全清楚课程在这个时候做得不多,但我无法继续,直到我解决问题为止。有人可以解释我做错了吗?

import sys
import boto  
import boto.ec2 

class Monitor:

    def __init__(self,conn,identifier):
        self.connection = conn
        self.identifier = identifier
        self.dispatcher ={'1': instance_status_check}

    def user_menu():
        for i, value in self.dispatcher.itertems():
            print "Please press {i} for {value}".format(i,value)

    def instance_status_check():
        pass    

2 个答案:

答案 0 :(得分:2)

您错过了这两种方法的self参数,而iteritems不是itertems

class Monitor:  # upper case for class names
    def __init__(self,conn,identifier):
        self.connection = conn
        self.identifier = identifier
        self.dispatcher ={'1': self.instance_status_check} # call self.instance_status_check()

    def user_menu(self): # self here
        for i, value in self.dispatcher.iteritems():
            print("Please press {i} for {value}".format(i,value))

    def instance_status_check(self): # self here
        return "In status method"

m = Monitor(3,4)
print(m.dispatcher["1"]())
In status method

我建议您查看docs

中的课程教程

答案 1 :(得分:0)

您有此错误,因为您已经在使用它之后定义了instance_status_check

将声明移到课程上方:

def instance_status_check():
    pass 

class monitor:

    def __init__(self,conn,identifier):
        self.connection = conn
        self.identifier = identifier
        self.dispatcher ={'1': instance_status_check}

    def user_menu(self):
        for i, value in self.dispatcher.itertems():
            print "Please press {i} for {value}".format(i,value)

此外,这不会打印Please press 1 for instance_status_check它会打印Please press 1 for <function instance_status_check at 0xsomething>

之类的内容