James Franco James Franco - 4 years ago 71
Python Question

Understanding scoping rules of python - using foo.var , self.var and var

Suppose I have the following code

class foo:
str = "Hello World"
def test(self):

a = foo()

I wanted to know if
can actually access the str variable ? If so why does the output only display

<type 'str'>

Now I have been reading about python for a little while but I am confused with this situation. I understand that if I did something like the following


python would initially look in the instance for a variable called
and if the variables is not found then it would look for class variables otherwise if I wanted to access the class variable directly I would use


so my question is which variable is being accessed with

same as using

Answer Source

You are confused because you picked the wrong variable name. str is the built-in string type. You have to use self. prefix within your class methods and instance prefix outside them.

class foo:      
  s = "Hello World"
  def test(self):
    print(s)   # s not found
    print(self.s)  # OK!

Note that you defined a class variable, shared between instances of the same class (with wierd effects sometimes). Reserve that usage to constants.

To define an instance variable do:

class foo:    
  def __init__(self):  
      self.s = "Hello World"

So you can change s on instance A without risking to change it on instance B (well it's different for immutables like strings or ints, but you don't want to do that anyway)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download