在局部函数变量期间更改了Python类实例 [英] Python class instance changed during local function variable

查看:41
本文介绍了在局部函数变量期间更改了Python类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我们定义一个类和一个函数

Let's for example define a class and a function

class class1(object):
    """description of class"""
    pass

def fun2(x,y):
    x.test=1;
    return x.value+y

然后定义一个类实例并将其作为函数中的局部变量运行

then define a class instance and run it as a local variable in the function

z=class1()
z.value=1
fun2(z,y=2)

但是,如果您尝试运行代码

However, if you try to run the code

z.test

将返回结果1.

那是,尽管x的属性是在fun2()本地内部完成的,但它也扩展到全局实例类x.这似乎违反了有关python函数的第一件事,除非将参数定义为非本地或全局参数,否则该参数将保持局部状态.

That was, though the attribute to x was done inside the fun2() locally, it extended to class instance x globally as well. This seemed to violate the first thing one learn about the python function, the argument stays local unless being defined nonlocal or global.

这怎么可能发生?为什么函数内部的class属性会扩展到函数外部.

How could this happen? Why the attribute to class inside a function extend outside the function.

推荐答案

我什至有一个比较陌生的例子:

I have even stranger example:

def fun3(a):
    b=a
    b.append(3)
    
mya = [1]
fun3(mya)

print(mya)

[1, 3]
> 

我复制"将该数组转换为局部变量,当我对其进行更改时,全局变量也将发生变化.

I "copy" the array to a local variable and when I change it, the global one changes as well.

问题在于参数未通过值(基本上作为值的副本)传递.在python中,它们通过引用传递.在 C 术语中,该函数获取指向内存位置的指针.这样可以更快.

The problem is that the parameters are not passed by a value (basically as a copy of the values). In python they are passed by reference. In C terminology the function gets a pointer to the memory location. It's much faster that way.

某些语言不允许您使用实例的私有属性,但是在Python中,您有责任确保不会发生这种情况.OOP的另一条规则是,仅应通过调用实例的方法来更改其内部状态.但是您可以直接更改值.

Some languages will not let you to play with private attributes of an instance, but in Python it's your responsibility to make sure that does not happen. One other rule of OOP is that you should change the internal state of an instance just by calling its methods. But you change the value directly.

Python非常灵活,甚至可以使您做坏事.但这不会推你.

Python is very flexible and allows you to do even the bad things. But it does not push you.

我总是争辩说,至少对任何高级语言的底层结构(内存模型,如何传递变量等)至少具有模糊的理解.关于C/C ++的知识还有另一个论点.大多数高级语言都是用它们编写的,或者至少受它们启发.C ++程序员会清楚地看到发生了什么.

I always argue to have always at least vague understanding of the underlaying structure of any higher level language (memory model, how the variables are passed etc.). There is another argument for having some C/C++ knowledge. Most of the higher level languages are written in them or at least are inspired by them. A C++ programmer would see clearly what is going on.

这篇关于在局部函数变量期间更改了Python类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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