python类 - 函数变量范围

时间:2017-09-05 18:47:29

标签: python oop scope

我有以下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__函数中定义。我需要在verticies_amount函数中使用Adjust_verticies_amount变量。但是,这是不可能的,因为它们在不同的范围内。因此,我的quadrilateral = triangle.Adjust_verticies_amount()电话无效。

我该如何正确地做到这一点?

1 个答案:

答案 0 :(得分:1)

您忘了在Polygon的 init ()方法中设置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()