一个类的多个实例同时被覆盖?(Python) [英] Multiple instances of a class being overwritten at the same time? (Python)

查看:37
本文介绍了一个类的多个实例同时被覆盖?(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我制作的非常简单的代码,用于演示遇到的问题.这里发生的是,我正在创建同一类的两个不同实例,但是更改一个实例的属性将更改另一个实例的对应属性.我不确定为什么会这样.在Python中这是正常现象吗?还是我遇到了一些完全搞砸了的东西?

Here's a very simple code I made to demonstrate the problem I'm encountering. What's happening here is that I'm creating two different instances of the same class but changing an attribute of one will change the corresponding attribute of the other instance. I'm not sure why this is. Is this normal in Python or am I encountering something being totally messed up?

class exampleClass(object):

    attribute1=0
    attribute2="string"

x=exampleClass
x.attribute1=20
x.attribute2="Foo"

y=exampleClass
y.attribute1=60
y.attribute2="Bar"

print("X attributes: \n")
print(x.attribute1)
print(x.attribute2)

print("Y attributes: \n")
print(y.attribute1)
print(y.attribute2)

这是从我的控制台出来的程序的样子:

Here is what the program looks like coming out of my console:

>>> 
X attributes: 

60
Bar
Y attributes: 

60
Bar
>>> 

我认为应该说:

X attributes:

20
Foo
Y attributes:

60
Bar

我在做什么错了?

推荐答案

当您需要实例属性时,您正在创建类属性.使用这个:

You're creating class attributes, when you want instance attributes. Use this:

class exampleClass(object):
    def __init__(self):
        self.attribute1 = 0
        self.attribute2 = "string"

此外,您没有创建exampleClass的任何实例,您需要这样做:

Also, you aren't creating any instances of exampleClass, you need this:

x = exampleClass()
y = exampleClass()

您的代码只是为该类使用新名称,并更改其属性.

Your code is simply using new names for the class, and changing its attributes.

这篇关于一个类的多个实例同时被覆盖?(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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