Python,避免覆盖函数的参数

问题描述 投票:2回答:2

我是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)
python function arguments
2个回答
3
投票

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

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

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


4
投票

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

inBoundary.pop

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

def triangularize(inBoundary):
    inBoundary = list(inBoundary)
    # proceed as before
© www.soinside.com 2019 - 2024. All rights reserved.