The attributes directly declared in a class are called class attributes.
Like in your example(though indentation and some syntax is wrong), value1 , value2 and value3 are class attributes for class gaurab.
Attributes declared inside other attributes are instance attributes and are bound to the class attribute in which they are declared.
Like the value1 and value2 variables are bound to init in class something.
The class attributes are compared to static variables found in statically typed languages as C++, JAVA etc.
Class attributes are shared by all the instances of class so only one copy of such attributes is made (unlike for instance attributes where each instance of class has its own copy of instance variables).
When instance of class something
is made, something
's __init__
method is executed, receiving the new instance in its self
parameter. This method creates two instance attributes: value1
and value2
. Then this instance is assigned into the instance variable, so it's bound to a thing with those two instance attributes.
For example :
class foo:
def __init__(self):
self.Alist=[] #It is an instance attribute
Blist=[] #It is a class attribute
For this class definition, when we create 2 class instances as :
var1 = foo()
var2 = foo()
The Blist
attribute is shared by both var1
and var2
but Alist
attribute is different for both of them. So, if we operate the following :
var1.Alist.append(1)
var1.Blist.append(10)
var2.Alist.append(2)
var2.Blist.append(20)
The output of
print(var1.Alist)
print(var1.Blist)
print(var2.Alist)
print(var2.Blist)
will be :
[1]
[10]
[2]
[10,20]
This is because Blist
variable was shared by both var1
and var2
So, changes in var1.Blist
affected var2.Blist
and vice versa.
But, var1.Alist
and var2.Alist
are independent of each other.
So, if you want an attribute to be common to all the instances of the class, then you declare it as class attribute(which if not what is often required) else, you can declare it as instance attribute.