实例方法中的类成员变量可见性

时间:2017-03-18 06:33:37

标签: python python-2.7

>>> class Triangle(object):
...     number_of_sides = 3
...     def __init__(self, angle1, angle2, angle3):
...         self.angle1 = angle1
...         self.angle2 = angle2
...         self.angle3 = angle3
...     def check_angles(self):
...         return True if self.angle1 + self.angle2 + self.angle3 == 180 else False
... 
>>> class Equilateral(Triangle):
...     angle = 60
...     def __init__(self):
...         self.angle1 = angle
...         self.angle2 = angle
...         self.angle3 = angle
... 
>>> 
>>> e = Equilateral()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
NameError: global name 'angle' is not defined

令人惊讶的是,这段代码给出了一个例外。为什么angle未被定义?

问题是我如何访问angle,问题是为什么angle无法访问?

2 个答案:

答案 0 :(得分:2)

尝试使用Equilateral.angle代替angle

class Equilateral(Triangle):
    angle = 60
    def __init__(self):
        self.angle1 = Equilateral.angle
        self.angle2 = Equilateral.angle
        self.angle3 = Equilateral.angle

答案 1 :(得分:2)

也许您可以使用self.angle

就像这样:

class Equilateral(Triangle):
     angle = 60
     def __init__(self):
         self.angle1 = self.angle
         self.angle2 = self.angle
         self.angle3 = self.angle

但我认为第一个答案更好,(我在提交答案后看到了)。我的答案可以解决,因为 init ()会找到我班级的角度无法找到我的物体的角度。 这是一个演示:

class test():
    angle = 0
    def __init__(self):
        self.angle1 = self.angle  # when __init__() run,it can't find a angle of your object,
                                  # so it will go to find the global angle in your class

    def show(self):
        print self.angle1

    def change(self):
        self.angle = 1   # this self.angle is a val of the object
        print self.angle

    def change_class(self):
        test.angle = 1   # if you want to change the angle of your class,this can be worked

a = test()
a.show()
a.change()
b = test()
b.show()
b.chenge_class()
c = test()
c.show()