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 
1
  • 1
    Those are class variables. You can access them with self, like self.foo Commented Jun 28, 2015 at 6:55

1 Answer 1

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() 
Sign up to request clarification or add additional context in comments.

2 Comments

why should I add a constructor to class ? Like java, python won't take care of this, by adding a default constructor ?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.