[英]pythonic way of modifying a mutable inside an immutable
let's say I have a class that behaves as an int to the outside world, but in fact is a mutable object that has a fixed place within several structures. 假设我有一个类,其行为与外界一样,但实际上是一个可变对象,在多个结构中具有固定位置。 if n is my object, I can update it now by writing n.update(34)
, but I find I'm always wanting to write n = 34
instead. 如果n是我的对象,我现在可以通过编写n.update(34)
来更新它,但我发现我一直想写n = 34
。 I've glanced over http://docs.python.org/reference/datamodel.html , and don't see anything like an __assign__ or __value__ attribute that would let me trap the =
operator and allow me to update my object rather than assign an int to the variable n, throwing my object away. 我浏览了http://docs.python.org/reference/datamodel.html ,看不到__assign__或__value__属性之类的东西,这些属性会让我捕获=
运算符并允许我更新我的对象而不是将int赋给变量n,将我的对象丢掉。 better still, when a mutable is inside a tuple t = (m, n)
, I would like to update my mutable with t[1] = 34
, but Python sees that as attempting to modify an immutable. 更好的是,当一个可变变量在一个元组t = (m, n)
,我想用t[1] = 34
更新我的可变变量,但是Python认为这是试图修改一个不可变变量。
so I guess the answer would be, based upon what little of that document I was able to grok, that what I'm attempting is not Pythonic. 所以我想答案是,根据我只能浏览的文件很少,我尝试的不是Pythonic。 so if I can't do it the way I want, what would be the next best thing? 因此,如果我无法按照自己的意愿进行操作,那么下一件最好的事情是什么? such that if someone has to maintain my code someday, it won't be overly offensive. 这样,如果某人必须某天维护我的代码,就不会过于冒犯。
Your basic obj.value = newvalue
is basically the best, most understandable way. 基本的obj.value = newvalue
基本上是最好的,最容易理解的方式。 As you surmise, it is not possible to override assignment in Python. 如您所料,不可能在Python中覆盖赋值。
You could implement __call__()
on your class to do the assignment, so that you can just do obj(newvalue)
. 您可以在您的类上实现__call__()
进行赋值,这样就可以执行obj(newvalue)
。 However, it's not at all clear to the casual reader that that's a reassignment. 但是,对于临时读者来说,这根本不是重新分配。
Another idea would be to implement __ilshift__()
so you can do obj <<= newval
. 另一个想法是实现__ilshift__()
以便您可以执行obj <<= newval
。 That at least looks like some kind of mutant reassignment operation if you squint hard enough. 如果您斜视一下,那至少看起来像是某种突变的重新分配操作。 If it weren't a numeric type, I might consider it. 如果不是数字类型,我可能会考虑。 But <<
has a well-defined meaning with int
and, since you're masquerading as that type, it would IMHO be confusing to use it in this way. 但是<<
与int
有着明确定义的含义,并且由于您是在伪装成这种类型,因此恕我直言,以这种方式使用它会令人困惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.