其中哪些在Python中是不可变的? [英] Which of these are immutable in Python?
问题描述
我试图弄清楚以下内容在Sage中是否是不可变的(它是基于Python构建的,因此我相信如果它在python中是不可变的,我相信在大多数情况下它将在Sage中是不可变的)
I am trying to figure out whether the following are immutable in Sage (which is built on Python so I believe if it is immutable in python, I believe in most cases it will be immutable in Sage)
下面是对象e,f,g,i
Below are objects e, f, g, i
class e: pass
f = e()
g = pi # (g's "type" in Sage is symbolic expression. It's supposed to be 3.1415....etc)
i = lambda x: x*x
我认为e是一个类,这意味着它是可变的(不可变的类有意义吗?难道不是所有类都可以修改吗?).由于f是类的实例,所以我猜测它也是可变的,因为类是可变的.
I gather that e is a class which means it is mutable (Does an immutable class make sense? Can't all classes be modified?). Since f is an instance of a class, I am guessing it is also mutable since classes are mutable.
由于数字在Python中是不可变的,因此g也应该是不可变的,因为尽管它是非理性的,但g是一个数字
Since numbers are immutable in Python, g should be immutable as well since it is a number despite being irrational
最后,我是一个函数,这意味着它应该是可变的?
Finally i is a function which means it should be mutable?
我不太确定我了解不变性的概念.函数不可变意味着什么?要让一个类是不变的?
I'm not quite sure I understand that concept of immutability. What would it mean for a function to be immutable? For a class to be immutable?
推荐答案
e
是可变的.例如,您可以在类上添加新方法:e.foo = lambda self,x: x
.
e
is mutable. You can, for instance, add a new method on the class: e.foo = lambda self,x: x
.
f
是可变的.例如,您可以向该类实例添加一个新字段:f.x = 99
.
f
is mutable. You can, for instance, add a new field to this class instance: f.x = 99
.
g
是不可变的.您对此无能为力.
g
is immutable. You can't change anything about it.
i
不是不可变的.您可以对它进行各种邪恶的事情:i.func_code = (lambda x: 123).func_code
之后,i(10)
将是123,而不是100.(您也可以对其进行更合理的处理.i.__doc__ = "This function returns the square of its argument."
之后,您将从i.__doc__ = "This function returns the square of its argument."
获得更有用的结果c9>.)
i
is not immutable. You can do all sorts of evil things to it: i.func_code = (lambda x: 123).func_code
after which i(10)
will be 123 instead of 100. (You can also do more reasonable things to it. After i.__doc__ = "This function returns the square of its argument."
you will get a more helpful result from help(i)
.)
如果您可以对某个对象执行某些操作以更改其将来的行为,则该对象是可变的.您不能更改10
的行为.您可以更改功能对象,类,类实例或列表的行为. (但不是元组.一旦创建了元组,它就会一直存在直到存在.)
An object is mutable if there's something you can do to the object that changes its possible future behaviour. You can't change the behaviour of 10
; you can change the behaviour of a function object, or a class, or a class instance, or a list. (But not a tuple. Once a tuple is made, it stays just as it is for as long as it exists.)
这篇关于其中哪些在Python中是不可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!