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

问题描述

我正在尝试自学Python,并且大部分时间都做得不错。但是,当我尝试运行代码

I'm trying to teach myself Python, and doing well for the most part. However, when I try to run the code

class Equilateral(object):
    angle = 60
    def __init__(self):
        self.angle1, self.angle2, self.angle3 = angle

tri = Equilateral()

我收到以下错误:

Traceback (most recent call last):
  File "python", line 15, in <module>
  File "python", line 13, in __init__
NameError: global name 'angle' is not defined

可能有一个非常简单的答案,但是为什么会这样?

There is probably a very simple answer, but why is this happening?

推荐答案

self.angle1, self.angle2, self.angle3 = angle

应为

self.angle1 = self.angle2 = self.angle3 = self.angle

只是说 angle 使python寻找一个全局的 angle 变量不存在。您必须通过 self 变量来引用它,或者由于它是类级别的变量,所以您也可以说 Equilateral.angle

just saying angle makes python look for a global angle variable which doesn't exist. You must reference it through the self variable, or since it is a class level variable, you could also say Equilateral.angle

另一个问题是逗号分隔的 self.angleN s。当您以这种方式分配时,python将在等号的两侧寻找相同数量的零件。例如:

The other issues is your comma separated self.angleNs. When you assign in this way, python is going to look for the same amount of parts on either side of the equals sign. For example:

a, b, c = 1, 2, 3

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

05-28 02:34
查看更多