在 lisp 中,您可以说:
(setf (aref a 1) 5)
在 perl 中你可以说:
substr( $string, $start, $stop ) =~ s/a/b/g
在python中可能有这样的事情吗?我的意思是可以将函数结果用作左值(作为赋值操作的目标)吗?
不可以。在编译器级别明确禁止分配给函数调用的结果:
>>> foo() = 3
File "<stdin>", line 1
SyntaxError: can't assign to function call
然而,Python 语法中有两种特殊情况:
# Slice assignment
a = [1,2,3,4]
a[0:2] = 98, 99 # (a will become [98, 99, 3, 4])
# Tuple assignment
(x, y, z) = (10, 20, 30)
另请注意,在 Python 中存在语句/函数对偶性,并且赋值或扩充赋值 ( +=
, *=
...) 不仅是普通运算符,而且是语句并具有特殊规则。
此外,在 Python 中没有“指针”的一般概念......传递给函数一个存储位置的唯一方法是传递一个“setter”闭包,因为要找到一个可分配的位置,您需要使用显式名称,索引,或者如果该位置是对象实例成员,则您需要使用实例字典)。
# Pass the function foo where to store the result
foo( lambda value : setattr(myObject, "member", value) )
不,一般来说没有任何方法可以做到这一点。切片符号在有限的情况下很接近,因为您可以执行以下操作:
>>> a = [1, 2, 3]
>>> a[1:2] = [5, 6]
>>> a
[1, 5, 6, 3]
简而言之,没有。
但是,如果您定义__setitem__
,则可以分配给下标,例如
foo['subscript'] = 7
您可以从函数返回foo
(如果需要,还可以返回下标)。
container, subscript = whatevs()
container[subscript] = 7
或者,在一行中:
operator.setitem(*(whatevs()+(7,)))
见operator
。
一般来说,不(不要停止阅读!!!!)。请注意以下事项:
class test:
test = 4
test().test = 5
# we can no longer refer to the created object.
x = test().test = 6
x # 6
然而,做一些搜索我发现了这个(这看起来像不好的做法,但可用):
globals()["varname"] = 5
varname # 5
因此,将您的 Perl 与我的 Python 混合,我们得到:
globals()[substr( $string, $start, $stop )] = something
substr( $string, $start, $stop ) # something
# Note: wouldn't work because the function returns a string.
# I just don't know what the function returns.
# so exec("print " +substr( $string, $start, $stop ) I guess
# similarly, and possibly a little better practice
locals()["somethingdif"] = somethingelse
somethingdif # somethingelse
为了减轻大规模的否决,我应该提到你可以完全搞砸你的程序。但你可能知道这一点。"somevar" not in locals()
只需通过检查或确保在使用此方法时不会覆盖现有变量"somevar" not in globals()
。