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):
print(str)

a = foo()
a.test()


I wanted to know if
print(str)
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

self.str


python would initially look in the instance for a variable called
str
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

foo.str


so my question is which variable is being accessed with
print(str)

is
foo.str
same as using
str
?

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