我对什么是不可变类型感到困惑。我知道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__
类,但它未标记任何错误。 最佳答案
什么? float 是一成不变的吗?但是我不能
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]