Take the 2-minute tour ×

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?

share|improve this question
add comment

3 Answers

up vote 6 down vote accepted
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
share|improve this answer
add comment

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


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
share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer


