不可变与可变类型 [英] Immutable vs Mutable types

查看:92
本文介绍了不可变与可变类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对什么是不可变类型感到困惑.我知道float对象是不可变的,在我的书中有这种类型的示例:

I'm confused on what an immutable type is. I know the float object is considered to be immutable, with this type of example from my book:

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

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

Is this considered to be immutable because of the class structure / hierarchy?, meaning float is at the top of the class and is its own method call. Similar to this type of example (even though my book says dict is mutable):

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

某些可变的类在类内部具有方法,例如以下类型:

Whereas something mutable has methods inside the class, with this type of example:

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


此外,对于最后一个class(SortedKeyDict_a),如果我将以下类型的set传递给它:


Also, for the last class(SortedKeyDict_a), if I pass this type of set to it:

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

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

without calling the example method, it returns a dictionary. The SortedKeyDict with __new__ flags it as an error. I tried passing integers to the RoundFloat class with __new__ and it flagged no errors.

推荐答案

什么?浮游物是一成不变的吗?但是我不能

What? Floats are immutable? But can't I do

x = 5.0
x += 7.0
print x # 12.0

那不是"mut" x吗?

Doesn't that "mut" x?

您是否同意字符串是不可变的,对吗?但是你可以做同样的事情.

Well you agree strings are immutable right? But you can do the same thing.

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

变量的值会更改,但是它会通过更改变量所指的内容而更改.可变类型可以更改这种方式,并且也可以就地"更改.

The value of the variable changes, but it changes by changing what the variable refers to. A mutable type can change that way, and it can also change "in place".

这是区别.

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]

这篇关于不可变与可变类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆