为什么Python似乎将实例变量视为对象之间共享的变量? [英] Why does Python seem to treat instance variables as shared between objects?

查看:78
本文介绍了为什么Python似乎将实例变量视为对象之间共享的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,当我注意到Python处理实例变量的方式出现一个奇怪的怪癖时,我正在研究一个简单的脚本.

I was working on a simple script today when I noticed a strange quirk in the way Python treats instance variables.

假设我们有一个简单的对象:

Say we have a simple object:

class Spam(object):
    eggs = {}

    def __init__(self, bacon_type):
        self.eggs["bacon"] = bacon_type

    def __str__(self):
       return "My favorite type of bacon is " + self.eggs["bacon"]

然后我们使用单独的参数创建该对象的两个实例:

And we create two instances of this object with separate arguments:

spam1 = Spam("Canadian bacon")
spam2 = Spam("American bacon")

print spam1
print spam2

结果令人困惑:

My favorite type of bacon is American bacon
My favorite type of bacon is American bacon

似乎鸡蛋"字典在所有不同的垃圾邮件"实例之间共享-要么在每次创建新实例时被覆盖.这并不是日常生活中的真正问题,因为我们可以通过在初始化函数中声明实例变量来解决它:

It seems like the "eggs" dictionary is shared between all the different "Spam" instances -- either that or it is overwritten every time a new instance is created. This isn't really a problem in every day life, since we can solve it by declaring the instance variable in the initialization function:

class Spam(object):

    def __init__(self, bacon_type):
        self.eggs = {}
        self.eggs["bacon"] = bacon_type

    def __str__(self):
        return "My favorite type of bacon is " + self.eggs["bacon"]

spam1 = Spam("Canadian bacon")
spam2 = Spam("American bacon")

print spam1
print spam2

使用这种方式编写的代码,结果就是我们所期望的:

With the code written this way, the result is what we expect:

My favorite type of bacon is Canadian bacon
My favorite type of bacon is American bacon

因此,尽管我不受这种行为的束缚,但我不明白为什么Python这样工作.谁能对此有所启发?

So while I'm not held up by this behavior, I don't understand why Python works this way. Can anyone shed some light on this?

推荐答案

正如Ignacio所说,在Python中的类作用域分配的变量是类变量.基本上,在Python中,类只是class语句下的语句列表.一旦该语句列表执行完毕,Python就会搜集在执行过程中创建的所有变量,并从中创建一个类.如果需要实例变量,则实际上必须将其分配给实例.

As Ignacio has posted, variables which are assigned to at class scope in Python are class variables. Basically, in Python, a class is just a list of statements under a class statement. Once that list of statements finishes executing, Python scoops up any variables that were created during the course of that execution and makes a class out of them. If you want an instance variable, you actually do have to assign it to the instance.

另一方面,听起来似乎是从Java(或类似Java)的角度来看的.所以也许您知道,因为Java要求显式声明变量,所以它需要在类范围内具有实例变量声明.

On another note: it sounds like you may be coming to this from a Java (or Java-like) perspective. So perhaps you know that because Java requires variables to be explicitly declared, it needs to have instance variable declarations at class scope.

class Foo {
    String bar;
    public Foo() {
        this.bar = "xyz";
    }
}

请注意,只有声明在类范围内.换句话说,为该变量分配的内存是模板"类的一部分,但该变量的实际 value 不是.

Note that only the declaration is at class scope. In other words, the memory allocated for that variable is part of the class "template," but the actual value of the variable is not.

Python不需要变量声明.因此,在Python翻译中,您只需删除声明即可.

Python doesn't have any need for variable declarations. So in the Python translation, you just drop the declaration.

class Foo:
    # String bar;  <-- useless declaration is useless
    def __init__(self):
        self.bar = "xyz"

将在需要时分配内存;实际上只写出了作业.就像在Java中那样,它进入了构造函数.

The memory will be allocated when it's needed; only the assignment is actually written out. And that goes in the constructor, just like in Java.

这篇关于为什么Python似乎将实例变量视为对象之间共享的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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