小编典典

Python-不可变类型与可变类型

python

我对什么是不可变类型感到困惑。我知道该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),如果我将这种类型的set传递给它:

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

不调用该example方法,它返回一个字典。在SortedKeyDict__new__其标记为错误。我尝试使用将整数传递给RoundFloat类,__new__并且它未标记任何错误。


阅读 631

收藏
2020-02-07

共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]
2020-02-07