2017-09-05 84 views
-1

我有以下Python代碼:蟒類 - 函數變量範圍

class Geometry_2D: 
    def __init__(self, shape_name): 
     self.shape_name = shape_name 

class Polygon(Geometry_2D): 

    def __init__(self, shape_name, verticies_amount): 
     Geometry_2D.__init__(self, shape_name) 
     self.verticies_amount 

    def Adjust_verticies_amount(self): 
     self.verticies_amount += 1 

triangle = Polygon('triangle', 3) 
quadrilateral = triangle.Adjust_verticies_amount() 

這裏我有一個可變verticies_amount其在Polygon__init__函數來定義。我需要在Adjust_verticies_amount函數中使用verticies_amount變量。但是,這是不可能的,因爲它們處於不同的範圍。所以,我的quadrilateral = triangle.Adjust_verticies_amount()調用不起作用。

我應該怎麼做才能正確?

+1

你只是忘了申報'self.verticies_amount = verticies_amount' – PRMoureu

+1

你忘了分配給'self.verticies_amount'在你的'Polygon'' __init__'中。將來,說「不起作用」不是一個充分的問題規範。你的程序在下面一行會失敗:'triangle = Polygon('triangle',3)',它會給你一個'AttributeError' –

回答

1

你忘了把self.vertices_amount在初始化()多邊形

的方法
class Geometry_2D: 
    def __init__(self, shape_name): 
     self.shape_name = shape_name 

class Polygon(Geometry_2D): 
    def __init__(self, shape_name, verticies_amount): 
     Geometry_2D.__init__(self, shape_name) 
     self.verticies_amount = vertices_amount 

    def Adjust_verticies_amount(self): 
     self.verticies_amount += 1 

triangle = Polygon('triangle', 3) 
quadrilateral = triangle.Adjust_verticies_amount()