English 中文(简体)
为什么灰色似乎把变数作为物体之间的共有物来处理?
原标题:Why does Python seem to treat instance variables as shared between objects?

我今天正在用简单的文字做工作,当时我注意到在山谷处理场变量方面存在着奇怪的qui。

我们有一个简单的目标:

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"]

我们用单独的论点制造了两例反对:

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

print spam1
print spam2

The results are puzzling:

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

似乎像“蛋”字典一样,在所有不同的“方言”情况下——无论在出现新情况时,这种说法还是过时的。 这在日常生活中确实是一个问题,因为我们能够通过宣布初始化职能中的事例变数来解决:

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

通过这一方式撰写的法典,我们期望的是:

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

因此,虽然我不听从这一行为,但我不理解为什么斯图尔这样做。 谁能对此有所了解?

最佳回答

正如伊格纳西奥所显示的那样,被分配到“富尔”类别范围的变量是类别变量。 基本上,在沙尔,一类仅是一份在<条码>栏说明下的发言清单。 这份声明清单一旦完成执行,就可归纳出执行过程中产生的任何变量,并从中分类。 如果你想要一个案例,那么你实际上就不得不把案件分配给了。

还有一点:从 Java(或类似 Java)的角度来看,它同你一样。 因此,或许你知道,由于 Java要求明确宣布变量,它需要在类别范围内提出可变的申报。

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

请注意,只有申报<>>属于班级范围。 换言之,为这一变量分配的memory是“template,”类别的一部分,但实际的 数值不是。

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一样,这一点也出现在建筑商。

问题回答

这并非偶然的变数,而是类别变量。 正在通过审理获得这一信息是无关的;它仍然是同一个目标。

与汇编语言不同的是,<代码>密特/代码>在俄亥俄语中的讲话实际上是穿着的,并产生一种记忆中的一类物体(不是一例!)。

在<代码>}栏块上界定的任何符号都属于该类别本身。 这包括各种变量,如:eggs,在您的第一例中可变,以及_init___str_,由您界定。 所有这一切都是在课堂定义时创造的,都是班级的一部分。

在您实际创建物体和<代码>_init_之前,不产生任何类型的变数。 这种方法是有效的,其 是<条码>的属性。

因此,当传译员处决时

class Spam(object):
    eggs = {}

    def __init__(self):
        <stuff>
    def __str__(self):
        <other stuff>

它实际上正在建造一个班级物体。 该编码执行“eggs={>”,实施两项def声明,并设置一个具有三个特性的类别:eggs,_init

后来,当它执行时

spam1 = Spam()

然后,它创立了一个新案例,并使用_init__方法。 www.un.org/Depts/DGACM/index_french.htm 当然,这种方法本身属于这一类别;它在所有情况下都分享,就像<编码>蛋/代码>属性。

例例本身作为<代码>自行参数通过,你对此加以定义的任何内容仅属于这种情况。 因此,<代码>自封/代码> 每一类方法必须采用——在下午,这些方法实际上属于类别本身,而<代码>本身是你必须提及这种情况的唯一途径。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...