0

How python recognize class and instance level variables ? 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 a.i (or b.i) and abc.i are they referring to completely different variables?

4

3 回答 3

2

首先,您的示例是错误的,因为如果__init__.

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

然后,当您访问实例上的属性时,它将首先检查实例变量。请参阅此处的段落。正如你猜测的那样:

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

此外,类变量是所有实例共享的对象,实例变量归实例所有:

>>> 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]
于 2013-08-08T04:03:22.087 回答
2

在上面的示例中,当我访问 ai(或 bi)和 abc.i 时,它们指的是完全不同的变量吗?

是的。

abc.i 是一个类对象引用。

ai 和 bi 是每个实例对象引用。

它们都是单独的参考。

于 2013-08-08T04:01:59.837 回答
1

这一切都假设您的 init 是:

def __init__(self,i):

否则,它不起作用。在第三种情况下,abc.i 类尚未初始化,因此 i 充当静态变量,您在类定义中将其值设置为 10。在前两个实例中,当您调用 init 时,您创建了一个具有特定 i 值的 abc 实例。当您询问每个实例的 i 值时,您会得到正确的数字。

于 2013-08-08T03:57:56.790 回答