Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

python - Why am I getting a NameError when I try to access an attribute in my class?

I have this code with a class:

class Triangle(object):
    def __init__(self, side1, side2, side3):
        self.side1 = side1
        self.side2 = side2
        self.side3 = side3

    def perimeter(self):
        return "Perimeter = %s" % (side1 + side2 + side3)

a = Triangle(3, 4, 5)
print(a.perimeter())

Running this code throws an exception:

Traceback (most recent call last):
  File "untitled.py", line 12, in <module>
    print(a.perimeter())
  File "untitled.py", line 9, in perimeter
    return "Perimeter = %s" % (side1 + side2 + side3)
NameError: name 'side1' is not defined

How come I can't access side1 in the perimeter method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This line:

return "Perimeter = %s" %(side1 + side2 + side3)

should be:

return "Perimeter = %s" %(self.side1 + self.side2 + self.side3)

To return the value of member variables in python, self. must be before the member. This is why self is one of the required parameters for member methods. In many other languages such as C#, the passing of self is implied, so you don't have to manually write it into the code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...