python 全局名称“self”没有定义
刚刚开始学习Python,我确信这是一个愚蠢的问题,但我正在尝试这样的事情:
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 语句来引用不同方法的变量的方式美好的。
感谢您的帮助
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()
The error I am getting is:
NameError: global name 'self' is not defined
I saw this way of using the self statement to reference variables of different methods in some code I read that is working fine.
Thanks for the help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
self
是类中的自引用。您的代码不在类中,您只定义了函数。您必须将方法包装在一个类中,如下所示。要使用main()
方法,您首先必须实例化类的对象并调用该对象的函数。此外,您的函数
setavalue
应该位于__init___
中,即实例化对象时调用的方法。您可能应该考虑的下一步是将名称作为参数提供给 init,这样您就可以创建Name
类的任意命名的对象;)看看 Python 教程的类章节 an at 深入了解 Python 以获取更多参考。
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 methodmain()
, you first have to instantiate an object of your class and call the function on the object.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 theName
class ;)Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.
在 Python 中, self 是类的实例方法的第一个参数的常规名称,它始终是调用该方法的实例:
会给你类似的东西
In Python
self
is the conventional name given to the first argument of instance methods of classes, which is always the instance the method was called on:Will give you something like
如果您来自 Java 等语言,也许您可以在
self
和this
之间建立某种关联。 self 将是对调用该方法的对象的引用,但您需要首先声明一个类。尝试:你可以尝试一些Python基础教程,如下所示:Python指南
If you come from a language such as Java maybe you can make some kind of association between
self
andthis
.self
will be the reference to the object that called that method but you need to declare a class first. Try:You can try some Python basic tutorial like here: Python guide
它应该是这样的:
It should be something like:
self
名称用作类实例中的实例引用。它仅用于类方法定义中。不要在函数中使用它。您也不能使用它从其他函数或方法引用局部变量。您只能使用它来引用实例或类属性。
The
self
name is used as the instance reference in class instances. It is only used in class method definitions. Don't use it in functions.You also cannot reference local variables from other functions or methods with it. You can only reference instance or class attributes using it.