Understanding python class attributes

python, python-2.7, python-3.x

Solution

`bar` is a class attribute. Since classes in Python are objects, they too can have attributes. `bar` just happens to live on that `Test` object, not an instance thereof.

Because of the way Python resolves attribute lookups, it looks like `test1` has a `bar` attribute, but it doesn't.

`foo` on the other hand lives on the instance `test1` after calling `display(80)`. This means that different instances of `Test`can have different values in their respective `foo` attributes.

Of course, you could use class variables as some kind of "shared default value", which you can then "override" with an instance attribute, but that might get confusing.

Second question

def display(self,foo):
    self.foo=foo
    foo = foo
    print "self.foo : ",self.foo 
    print "foo : ",foo 

Let's just get a detail out of the way: `self` is not a keyword, it's just convention to call the first argument "self", you could also call it "this" or "that" or "bar" if you liked, but I wouldn't recommend that.

Python will pass the object, on which the method was called as the first argument.

def display(self,foo): 

This foo is the name of the first parameter of the display instance-function.

    self.foo=foo

This sets the attribute with the name "foo" of the instance, on which you called `display()` to the value, which you passed as first argument. Using your example `test1.display(80)`, `self` will be `test1`, `foo` is `80` and `test1.foo` will thus be set to `80`.

    foo = foo

This does nothing at all. It references the first parameter `foo`.

The next two lines again reference the instance variable `foo` and the first parameter `foo`.

Problem

I am very new to programming and started learning python. Might look very stupid question, so please pardon my ignorance. Consider the following snippet of code : ``` class Test1: bar = 10 def display(self,foo): self.foo=foo print "foo : ",self.foo #80 def display1(self): print "bar: ", self.bar #10 print "again foo: ", self.foo #80 if __name__ == '__main__': test1 = Test1() test1.display(80) test1.display1() print test1.bar #10 print test1.foo #80 ``` I want to understand what is the difference between using foo and bar (wrt to where we have defined them) as in scope wise they are equally accessible at all places compared to each other and only difference is that one is inside function and other is inside Class but they both are still "instance" variable. So which is good practice? Also, if I slightly modify display function as below : ``` def display(self,foo): self.foo=foo foo = foo print "self.foo : ",self.foo print "foo : ",foo ``` Can someone please explain how python sees this, as in what difference/significance this `self` keyword is bringing in between two `foo`.

Original source