为什么当我尝试访问班级中的属性时会收到 NameError?

问题描述

我有这个类的代码:

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

perimeter方法中怎么访问不到side1?


解决方案

替换

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

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

你错过了添加self

相关文章