2017-03-18 35 views
0
>>> 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无法访问?

+0

use'ClassName.class_attribute' –

回答

2

尝试使用Equilateral.angle而不是angle

class Equilateral(Triangle): 
    angle = 60 
    def __init__(self): 
     self.angle1 = Equilateral.angle 
     self.angle2 = Equilateral.angle 
     self.angle3 = Equilateral.angle 
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() 
相关问题