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?
should be
just saying
angle
makes python look for a globalangle
variable which doesn't exist. You must reference it through theself
variable, or since it is a class level variable, you could also sayEquilateral.angle
The other issues is your comma separated
self.angleN
s. 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:While a, b, c = d is invalid, a = b = c = d works just fine.
You need to use
self.angle
here because classes are namespaces in itself, and to access an attribute inside a class we use theself.attr
syntax, or you can also useEquilateral.angle
here asangle
is a class variable too.Which is still wrong becuase you can't assign a single value to three variables:
Example: