蟒蛇;类实例 [英] Python; class instances

查看:192
本文介绍了蟒蛇;类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类,调用 class1,有3个类变量 var1,var2,var3, __ init __ 方法将传递的参数分配给类变量:

Suppose I have a class, call it class1, with 3 class variables var1,var2,var3, and __init__ method, which assigns passed arguments to the class variables:

class class1(object):
    var1 = 0
    var2 = 0
    var3 = 0

    def __init__(self,a,b,c):
       class1.var1 = a
       class1.var2 = b
       class1.var3 = c

现在我要创建同一个类的两个实例:

Now I'm going to make two instances of the same class:

obj1 = class1(1,2,3)
obj2 = class1(4,5,6)

现在,让我们来看看变量值:

And now, let's take a look at variables values:

print (obj1.var1, obj1.var2,obj1.var3)
4 5 6
print (obj2.var1, obj2.var2,obj2.var3)
4 5 6

不应 obj1 有值1,2,3吗?为什么第二个实例的 __ init __ 方法更改第一个实例中的值( obj1 )?

Shouldn't obj1 have values 1,2,3 ? Why __init__ method of the second instance changes vaues in the first instance(obj1)? And how to make two independent separate instances of a class?

推荐答案

在类定义中声明的变量,但不在内部方法,将是类变量

Variables declared in the class definition, but not inside a method, will be class variables. In other words, they will be the same for the whole class.

要解决这个问题,你可以在 __ init __ 方法,因此它们变成实例变量

To solve this you could declare them in the __init__ method, so they become instance variables:

class class1():
    def __init__(self,a,b,c):
        self.var1 = a
        self.var2 = b
        self.var3 = c

这篇关于蟒蛇;类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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