2017-03-18 63 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() 
相關問題