不可变与可变类型

新手上路,请多包涵

我对什么是不可变类型感到困惑。我知道 float 对象被认为是不可变的,以我书中的此类示例为例:

 class RoundFloat(float):
    def __new__(cls, val):
        return float.__new__(cls, round(val, 2))

由于类结构/层次结构,这是否被认为是不可变的?,意思是 float 位于类的顶部并且是它自己的方法调用。类似于此类示例(即使我的书说 dict 是可变的):

 class SortedKeyDict(dict):
    def __new__(cls, val):
        return dict.__new__(cls, val.clear())

而一些可变的东西在类中有方法,用这种类型的例子:

 class SortedKeyDict_a(dict):
    def example(self):
        return self.keys()


另外,对于最后一个 class(SortedKeyDict_a) ,如果我将这种类型的集合传递给它:

 d = (('zheng-cai', 67), ('hui-jun', 68),('xin-yi', 2))

不调用 example 方法,它返回一个字典。 SortedKeyDict__new__ 将其标记为错误。我尝试将整数传递给 RoundFloat__new__ 并且它没有标记错误。

原文由 user1027217 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 210
1 个回答

什么?浮动是不可变的?但我做不到吗

x = 5.0
x += 7.0
print x # 12.0

那不是“mut”x吗?

那么你同意字符串是不可变的吗?但是你可以做同样的事情。

 s = 'foo'
s += 'bar'
print s # foobar

变量的值发生变化,但它通过改变变量所指的内容而改变。可变类型可以那样改变, 可以“就地”改变。

这是不同之处。

 x = something # immutable type
print x
func(x)
print x # prints the same thing

x = something # mutable type
print x
func(x)
print x # might print something different

x = something # immutable type
y = x
print x
# some statement that operates on y
print x # prints the same thing

x = something # mutable type
y = x
print x
# some statement that operates on y
print x # might print something different

具体例子

x = 'foo'
y = x
print x # foo
y += 'bar'
print x # foo

x = [1, 2, 3]
y = x
print x # [1, 2, 3]
y += [3, 2, 1]
print x # [1, 2, 3, 3, 2, 1]

def func(val):
    val += 'bar'

x = 'foo'
print x # foo
func(x)
print x # foo

def func(val):
    val += [3, 2, 1]

x = [1, 2, 3]
print x # [1, 2, 3]
func(x)
print x # [1, 2, 3, 3, 2, 1]

原文由 morningstar 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题