繁体   English   中英

Python,避免覆盖函数的参数

[英]Python, Avoid overwriting argument to function

我是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中的列表是可变的,以及诸如的操作

inBoundary.pop

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

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

最简单的方法是复制传入的参数:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM