Jared Nielsen
Jared Nielsen

Reputation: 3897

Python Error: Global Name not Defined

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?

Upvotes: 2

Views: 15074

Answers (3)

user2701813
user2701813

Reputation: 9

While a, b, c = d is invalid, a = b = c = d works just fine.

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250901

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

Upvotes: 4

Ryan Haining
Ryan Haining

Reputation: 36792

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

Upvotes: 8

Related Questions