0

Can some one please help me with python lists. I created a global variable and global list. Updated global values in other methods. global value updated fine, but global list gave me an error.

class Practice(object):

    foo = []
    var = 0;

    def __updateVaribale(self):
       global var
       var = 9;

    def __updateList(self):
       global foo
       foo.append("updateList 1")


    def main(self):
      self.__updateVaribale();
      global var
      print(var)

      self.__updateList()
      global foo
      print(foo)

Obj = Practice();
Obj.main();       

output

 9
Traceback (most recent call last):
 File "Python Test\src\Practice.py", line 31, in <module>
Obj.main();
 File "Python Test\src\Practice.py", line 26, in main
self.__updateList()
  File "Python Test\src\Practice.py", line 18, in __updateList
foo.append("updateList 1")
NameError: name 'foo' is not defined
madhu_karnati
  • 785
  • 1
  • 6
  • 22

1 Answers1

2

You have created a class and so the variables of the class need to have the self prefix so that when the 'Obj' object is instantiated, its variables and methods belong to it (reference the bound object).

In addition to adding self to each variable (attribute) you need to add a constructor to your class.

See below:

class Practice():
    def __init__(self):
        self.foo = []
        self.var = 0;

    def __updateVaribale(self):
       self.var = 9;

    def __updateList(self):
       self.foo.append("updateList 1")


    def main(self):
      self.__updateVaribale();
      print(self.var)

      self.__updateList()
      print(self.foo)

Obj = Practice()
Obj.main()
sw123456
  • 3,339
  • 1
  • 24
  • 42
  • why should I add a constructor to class ? Like java, python won't take care of this, by adding a default constructor ? – madhu_karnati Jun 28 '15 at 07:20
  • Without the constructor the class will have no initialiser, and wont be automatically called when you create a new instance of a class. Within that function, the newly created object is assigned to the parameter self. Without it, any objects you create from the class will not be able to be passed into the class and thus the objects data will not be bound to the object. – sw123456 Jun 28 '15 at 07:25