简体   繁体   English

python:类变量和实例变量

[英]python: class variables and instance variables

How python recognize class and instance level variables ? python如何识别类和实例级别的变量? are they different ? 他们不同吗?

For example,

class abc:
    i = 10
    def __init__(self, i):
        self.i = i


a = abc(30)
b = abc(40)
print a.i
print b.i
print abc.i

output
--------
30
40
10

Means, in above example when I access ai (or bi) and abc.i are they referring to completely different variables? 意思是,在上面的示例中,当我访问ai (or bi)abc.i ,它们是指完全不同的变量吗?

in above example when I access ai (or bi) and abc.i are they referring to completely different variables? 在上面的示例中,当我访问ai(或bi)和abc.i时,它们是指完全不同的变量吗?

Yes. 是。

abc.i is a Class Object reference. abc.i是一个类对象引用。

ai and bi are each Instance Object references. ai和bi都是实例对象引用。

They are all separate references. 它们都是单独的参考。

First, your sample is wrong for you can not init the instance if there is only a self in the __init__ . 首先,您的示例是错误的,因为如果__init__只有一个自我,则无法初始化实例。

>>> class abc:
...     i = 10
...     j = 11
...     def __init__(self, x):
...             self.i = x

Then, when you access the attribute on the instance, it will check the instance variables first. 然后,当您访问实例上的属性时,它将首先检查实例变量。 Refer the paragraph here . 请参阅此处段落 As you guess: 如您所料:

>>> a = abc(30)
>>> a.i
30
>>> a.j
11

Besides, the class variables is an object shared by all the instances, and instance variables are owned by the instance: 此外,类变量是所有实例共享的对象,实例变量归实例所有:

>>> class abc:
...     i = []
...     def __init__(self, x):
...             self.i = [x]
...             abc.i.append(x)
... 
>>> a = abc(30)
>>> b = abc(40)
>>> a.i
[30]
>>> b.i
[40]
>>> abc.i
[30, 40]

This is all assuming your init is meant to be: 所有这些都假设您的init意图是:

def __init__(self,i):

Other wise it doesn't work. 否则,它是行不通的。 In the third case, abc.i the class hasn't been initialized so i acts as a static variable for which you set the value at 10 in the class definition. 在第三种情况下,abc.i类尚未初始化,因此我充当静态变量,您可以在类定义中将其设置为10。 In the first two instances, when you called init you created an instance of abc with a specific i value. 在前两个实例中,当您调用init时,您创建了一个具有特定i值的abc实例。 When you ask for the i value of each of those instances you get the correct number. 当您要求每个实例的i值时,您将获得正确的数字。

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

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