0

in python if i used a variable outside any class method it available throughout other methods and if i use the init method with self it basically does the same (or as it seems ) can anybody explain the difference between them . and when it is suitable to use either of the approach

class gaurab():
    value1=1
    value2=2
    value3=3

values=gaurab()

class something():
    def __init__(self):
        self.value1=1
        self.value2=100
    def p(self):
        print self.value1

svalues=something()

print values.value1

print svalues.p()
Legolas Bloom
  • 1,725
  • 1
  • 19
  • 17
cowboy
  • 75
  • 6
  • Your indentation is wrong! And you also want to look here: http://stackoverflow.com/questions/8959097/what-is-the-difference-between-class-and-instance-variables-in-python – elena Mar 26 '17 at 06:48

1 Answers1

0

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.

gaurav
  • 136
  • 1
  • 6