Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Error: Global Name not Defined

Tags:

python

class

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

I get the following error:

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?

like image 235
Jared Nielsen Avatar asked Jun 12 '26 01:06

Jared Nielsen


2 Answers

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

should be

self.angle1 = self.angle2 = self.angle3 = self.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

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
like image 62
Ryan Haining Avatar answered Jun 14 '26 15:06

Ryan Haining


You need to use self.angle here because classes are namespaces in itself, and to access an attribute inside a class we use the self.attr syntax, or you can also use Equilateral.angle here as angle is a class variable too.

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

Which is still wrong becuase you can't assign a single value to three variables:

self.angle1, self.angle2, self.angle3 = [self.angle]*3

Example:

In [18]: x,y,z=1  #your version
---------------------------------------------------------------------------

TypeError: 'int' object is not iterable

#some correct ways:

In [21]: x,y,z=1,1,1  #correct because number of values on both sides are equal

In [22]: x,y,z=[1,1,1]  # in case of an iterable it's length must be equal 
                        # to the number elements on LHS

In [23]: x,y,z=[1]*3
like image 28
Ashwini Chaudhary Avatar answered Jun 14 '26 14:06

Ashwini Chaudhary