是否可能像python中的perl的lvalue或lisp的setf之类的东西? [英] Is it possible something like lvalue of perl or setf of lisp in python?

查看:59
本文介绍了是否可能像python中的perl的lvalue或lisp的setf之类的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

轻率地说,你可以说:

(setf (aref a 1) 5)

在perl中,您可以说:

In perl you can say:

substr( $string, $start, $stop ) =~ s/a/b/g

在python中是否可能有类似的东西?我的意思是可以将函数结果用作左值(作为赋值操作的目标)?

Is it possible something like this in python? I mean is it possible to use function result as a lvalue (as a target for assignment operation)?

推荐答案

否.在编译器级别上,明确禁止分配函数调用的结果:

No. Assigning to the result of a function call is specifically prohibited at the compiler level:

>>> foo() = 3
  File "<stdin>", line 1
SyntaxError: can't assign to function call

但是Python语法中有两种特殊情况:

There are however two special cases in the Python syntax:

# 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中存在语句/函数对偶性,并且赋值或扩展赋值(+=*= ...)不仅是常规运算符,而且是语句,并有特殊规则.

Note also that in Python there is a statement/function duality and an assignment or an augmented assignment (+=, *= ...) is not just a normal operator, but a statement and has special rules.

此外,在Python中,没有指针"的一般概念...向函数传递存储内容的唯一方法是传递"setter"闭包,因为要找到需要使用的可分配位置显式名称,索引,或者如果该位置是对象实例成员,则需要使用实例字典.

Moreover in Python there is no general concept of "pointer"... the only way to pass to a function a place where to store something is to pass a "setter" closure because to find an assignable place you need to use explicit names, indexing or you need to work with the instance dictionary if the place is an object instance member).

# Pass the function foo where to store the result
foo( lambda value : setattr(myObject, "member", value) )

这篇关于是否可能像python中的perl的lvalue或lisp的setf之类的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆