美文网首页
Python 防止变量被隐式改变

Python 防止变量被隐式改变

作者: 一百万个不确定 | 来源:发表于2019-06-19 17:55 被阅读0次

    相关知识

    Python 的变量类型

    Python 的赋值机制

    同级变量隐式改变

    当两个变量指向同一个可变实例时,一个发生改变,另一个随之发生改变

    >>> origin = []
    >>> new = origin
    >>> origin.append('new_value')
    >>> print('origin value is: ', origin)
    origin value is:  ['new_value']
    >>> print('while new value is: ', new)
    while new value is:  ['new_value']
    

    这段代码里面,我只改变了origin的值,但是new的值也被改变了。

    如何避免?

    对可变类型永远使用copy

    import copy
    origin = []
    new = copy.copy(origin)
    origin.append('new_value')
    
    print('origin value is: ', origin)
    print('while new value is: ', new)
    

    执行结果

    origin value is:  ['new_value']
    while new value is:  []
    

    变量隐式改变指向

    在同一级别的对象传递还容易被识别,但是如果是不同级别的对象传递呢?

    def tricky_func(variable):
        variable.append('new_value')
        return variable
    
    
    origin = []
    new = tricky_func(origin)
    
    print('new list should have the new_value: ', new)
    print('but now the origin value also have it, which is not supposed: ', origin)
    

    执行结果

    new list should have the new_value:  ['new_value']
    but now the origin value also have it, which is not supposed:  ['new_value']
    

    你本希望new是一个全新的list,但是还是指向origin。非常要命的是,之后无论origin和new那个改变了值,都会引起另一个的改变。

    如何避免?

    调用函数的时候,使用copy之后再调用

    import copy
    def tricky_func(variable):
        variable.append('new_value')
        return variable
    
    origin = []
    new = tricky_func(copy.copy(origin))
    
    print('new list should have the new_value: ', new)
    print('now the origin is good: ', origin)
    

    现在的执行结果

    new list should have the new_value:  ['new_value']
    now the origin is good:  []
    

    相关文章

      网友评论

          本文标题:Python 防止变量被隐式改变

          本文链接:https://www.haomeiwen.com/subject/kdflqctx.html