class a(object):
b = 'bbbb'
def __init__(self):
self.c = 'cccc'
I think they are the same; is there any difference?
class a(object):
b = 'bbbb'
def __init__(self):
self.c = 'cccc'
I think they are the same; is there any difference?
Yes, there is a difference.
b
is a class variable... one that is shared by all instances of a
, while c
is an instance variable which will exist independantly for each instance.
'b' is a class attribute, set directly on the class object 'a'. 'c' is an instance attribute, set directly on self. While self.b
will find a.b
due to how lookup works, you cannot use a.c
(as it doesn't exist).
b
is a class variable, while c
is a instance variable.
>>> a.b
'bbbb'
>>> a.c
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'a' has no attribute 'c'
>>> a().b
'bbbb'
>>> a().c
'cccc'
Instances of the class may have different value for their instance variables, but they share the same class variables.
>>> class a(object):
... b = 'bbbb'
... def __init__(self):
... self.c = 'cccc'
...
>>> a1=a()
>>> a2=a()
>>> a1.b
'bbbb'
>>> a2.b
'bbbb'
>>> a1.c='dddd'
>>> a1.c
'dddd'
>>> a2.c
'cccc'
>>> a.b= 'common'
>>> a1.b
'common'
>>> a2.b
'common'