Python,避免覆盖函数的参数

时间:2013-09-19 07:55:05

标签: python function arguments

我是Python的新手,很惊讶地发现我的代码的这一部分:

print len(allCommunities[5].boundary)
allCommunities[5].surface = triangularize(allCommunities[5].boundary)
print len(allCommunities[5].boundary)

输出:

1310
2

下面是我在Processing(像Java这样的语言)中编写并移植到Python中的函数。它完成它应该做的(三角形多边形),但我的目的是通过inBoundary来使用函数但不删除allCommunities[5].boundary中的元素。

我应该如何防止在功能中修改allCommunities[5].boundary?在旁注中,如果我在函数中做一些愚蠢的事情,我会很感激指针,但仍然习惯于Python。

def triangularize(inBoundary):
    outSurface = []

    index = 0;
    while len(inBoundary) > 2:
        pIndex = (index+len(inBoundary)-1)%len(inBoundary);
        nIndex = (index+1)%len(inBoundary);

        bp = inBoundary[pIndex]
        bi = inBoundary[index]
        bn = inBoundary[nIndex]

        # This assumes the polygon is in clockwise order
        theta = math.atan2(bi.y-bn.y, bi.x-bn.x)-math.atan2(bi.y-bp.y, bi.x-bp.x);
        if theta < 0.0: theta += math.pi*2.0;

        # If bp, bi, and bn describe an "ear" of the polygon
        if theta < math.pi:
            inside = False;

            # Make sure other vertices are not inside the "ear"
            for i in range(len(inBoundary)):
                if i == pIndex or i == index or i == nIndex: continue;

                # Black magic point in triangle expressions
                # http://answers.yahoo.com/question/index?qid=20111103091813AA1jksL
                pi = inBoundary[i]
                ep = (bi.x-bp.x)*(pi.y-bp.y)-(bi.y-bp.y)*(pi.x-bp.x)
                ei = (bn.x-bi.x)*(pi.y-bi.y)-(bn.y-bi.y)*(pi.x-bi.x)
                en = (bp.x-bn.x)*(pi.y-bn.y)-(bp.y-bn.y)*(pi.x-bn.x)

                # This only tests if the point is inside the triangle (no edge / vertex test)
                if (ep < 0 and ei < 0 and en < 0) or (ep > 0 and ei > 0 and en > 0):
                    inside = True;
                    break

            # No vertices in the "ear", add a triangle and remove bi
            if not inside:
                outSurface.append(Triangle(bp, bi, bn))
                inBoundary.pop(index)
        index = (index+1)%len(inBoundary)
    return outSurface

print len(allCommunities[5].boundary)
allCommunities[5].surface = triangularize(allCommunities[5].boundary)
print len(allCommunities[5].boundary)

2 个答案:

答案 0 :(得分:4)

Python中的列表是可变的,以及诸如

之类的操作
inBoundary.pop

修改它们。简单的解决方案是复制函数内的列表:

def triangularize(inBoundary):
    inBoundary = list(inBoundary)
    # proceed as before

答案 1 :(得分:3)

最简单的方法是制作参数的副本:

def triangularize(origBoundary):
    inBoundary = origBoundary[:]

然后你的其余代码可以保持不变。