python全局名称'self'未定义 [英] python global name 'self' is not defined

查看:90
本文介绍了python全局名称'self'未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始学习 python,我确信这是一个愚蠢的问题,但我正在尝试这样的事情:

Just started learning python and I am sure its a stupid question but I am trying something like this:

    def setavalue(self):
        self.myname = "harry"

    def printaname():
        print "Name", self.myname     

    def main():
        printname()




    if __name__ == "__main__":
        main() 

我得到的错误是:

 NameError: global name 'self' is not defined

在我读过的一些代码中,我看到了这种使用 self 语句来引用不同方法的变量的方式.

I saw this way of using the self statement to reference variables of different methods in some code I read that is working fine.

感谢您的帮助

推荐答案

self 是类中的自引用.您的代码不在类中,您只定义了函数.您必须将方法包装在一个类中,如下所示.要使用main() 方法,您首先必须实例化类的一个对象并调用该对象上的函数.

self is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main(), you first have to instantiate an object of your class and call the function on the object.

此外,您的函数 setavalue 应该在 __init____ 中,该方法在实例化对象时调用.您可能应该考虑的下一步是将名称作为参数提供给 init,这样您就可以创建 Name 类的任意命名的对象;)

Further, your function setavalue should be in __init___, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name class ;)

class Name:
    def __init__(self):
        self.myname = "harry"

    def printaname(self):
        print "Name", self.myname     

    def main(self):
        self.printaname()

if __name__ == "__main__":
    objName = Name()
    objName.main() 

查看Python 教程的类章节深入 Python 以获取更多参考.

Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.

这篇关于python全局名称'self'未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆