本文介绍了尝试访问类中的属性时,为什么会出现NameError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有此类的代码:

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

为什么我无法通过perimeter方法访问side1?

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

推荐答案

替换

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

收件人

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

您错过了添加self

这篇关于尝试访问类中的属性时,为什么会出现NameError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 23:31