简体   繁体   English

蟒蛇; 类实例

[英]Python; class instances

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: 假设我有一个名为class1,的类,它带有3个类变量var1,var2,var3,__init__方法,该方法将传递的参数分配给类变量:

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

Shouldn't obj1 have values 1,2,3 ? obj1不应具有1,2,3的值吗? Why __init__ method of the second instance changes vaues in the first instance( obj1 )? 为什么第二个实例的__init__方法更改第一个实例( 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. 换句话说,它们对于整个班级都是相同的。

To solve this you could declare them in the __init__ method, so they become instance variables : 为了解决这个问题,您可以在__init__方法中声明它们,使它们成为实例变量

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

Class variables are shared by all instances of the class (and the class itself). 类变量由类的所有实例(以及类本身)共享。 You need to use instance variables instead. 您需要使用实例变量。

>>> class class1(object):
...     def __init__(self,a,b,c):
...        self.var1 = a
...        self.var2 = b
...        self.var3 = c
...
>>> obj1 = class1(1,2,3)
>>> obj2 = class1(4,5,6)
>>> print (obj1.var1, obj1.var2,obj1.var3)
(1, 2, 3)
>>> print (obj2.var1, obj2.var2,obj2.var3)
(4, 5, 6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM