2

I was wondering what was the difference between the Foo.var= user input and self.var= userinput in the 2 classes.

class foo():
    var=None

    def __init__(self,userinput):
        foo.var=userinput


class bar():
    var=None

    def __init__(self,userinput):
        self.var=userinput
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
Belrouk
  • 115
  • 1
  • 2
  • 10

3 Answers3

3

foo refers to the class, self refers to the object.

Class members are a property of the class (and thus are shared between all objects of that class), while instance members are a property of the specific object, so a change to an instance member affects only the given object.

When you operate on an object, the members it has are a merge of the class members and the instance members. When two members with the same name are defined, the instance members have the priority.

Thus:

  • bar sets an instance variable; that change has effect only on the current instance, so if you do:

    b=bar(10)
    c=bar(20)
    

    you'll see that c.var is 20 and b.var is 10; nothing strange here;

  • foo sets a class variable, which is common to all the instances; so, if you do:

    f=foo(10)
    g=foo(20)
    

    you'll see that both f.var and g.var will be 20, because they both actually refer to foo.var, that was last set to 20 in g's constructor;

  • on the other hand, instance variables shadow class variables; so, if you do

    f=foo(10)
    g=foo(20)
    f.var=30
    

    you'll have g.var==foo.var==20, but f.var==30, since now f.var refers to the instance variable f.var; but, if you do

    del f.var
    

    now the instance (f's) attribute var no longer exists, and thus f.var refers again to the class attribute var (thus f.var==g.var==foo.var==20).


Long story short: normally you'll want to use self.var (i.e. instance members); classname.var is only for sharing stuff between all instances of a given class.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
1

I'd like to point to an existing post which explains the difference perfectly in my opinion.

Python: Difference between class and instance attributes

Community
  • 1
  • 1
Saucier
  • 4,200
  • 1
  • 25
  • 46
0

Yes,

In the first instance you are setting the variable for all instances of foo this is because it is a class variable.

In the second case you are only setting the variable for that instance of foo.

For Example:

class pie():
    def __init__(self, j):
        pie.var = "pies" + str(j)
        print (self.var)

    def __str__(self):
        return self.var

a = pie(1)
b = pie(2)

print (a)
print (b)
Serdalis
  • 10,296
  • 2
  • 38
  • 58