在 Python 中:
a = "l[0], l[1], l[2], l[3]"
# l[0] etc. have their own value
my_function(a) #doesn't work
#but this does work
my_function(l[0], l[1], l[2], l[3])
字符串 a 可以“转换”以便函数看到变量吗?谢谢你。
稍后更新:感谢您回答我的问题。我包括了更大的问题以及为什么我不得不求助于 eval 函数(根据您的答案,这不是所需的)。功能:
class Line(object):
def __init__(self, pt1, pt2, *pt):
pt1 = Point(pt1[0],pt1[1])
pt2 = Point(pt2[0],pt2[1])
self.vertices = [pt1, pt2]
for i in pt:
self.vertices.append(Point(i[0],i[1]))
def __getitem__(self, key):
pt = self.vertices[key]
p = Point(p[0],p[1])
return p
#Here is the part with the issue:
def move(self, dx, dy):
pts = len(self.vertices)
l = self.vertices
pt1 = Point(Point(l[0].x, l[0].y).move(dx, dy).x, Point(l[0].x, l[0].y).move(dx, dy).y)
pt2 = Point(Point(l[1].x, l[1].y).move(dx, dy).x, Point(l[1].x, l[1].y).move(dx, dy).y)
if pts == 2:
mv = LineString(p1, p2)
if pts > 2:
bla = ''
for i in [2,pts]:
px = Point(l[i].x, l[i].y).move(dx, dy).x
py = Point(l[i].x, l[i].y).move(dx, dy).y
l[i] = Point(px,py)
bla += 'l[' + str(i) + '], '
arguments = bla[:-2]
mv = LineString(pt1, pt2, *eval(arguments))
return mv
根据您的回答,有更好的方法来解决这个问题..