3 Replies Latest reply: May 8, 2012 11:53 AM by Mark Szymczyk
iTryFreeApps Level 1 Level 1 (30 points)

I'm new to Python, and I need to make a meathod, but I do not want the variables to be just local (I think it's called instance variables, but I'm not sure). How can I make this variable public to my whole program, not just the meathod I'm making with the "def" keyword?


Xcode 3, Mac OS X (10.5.8)
  • Keith Barkley Level 5 Level 5 (5,665 points)

    I don't know python, but you can always create a method to set/read the variable.

     

    pseudocode:

     

    private int variable

     

    int getvar()

         return variable

     

    void setvar(int var)

         variable = var

  • iTryFreeApps Level 1 Level 1 (30 points)

    Well, I also need instance variables for loops. For example, I have a variable which I set during one of the loops. But when the program loops over again, the local variable's value is erased. I would like the variable to stay the same (every time it loops until the program is quit) once the variable is set.

  • Mark Szymczyk Level 4 Level 4 (1,935 points)

    Instance variables are members of Python classes. To create an instance variable for a Python class, declare the variable inside the class's __init__ method.

     

    From reading your question, it sounds like you want to use global variables, not instance variables. To create a global variable declare it outside a method. To modify a global variable inside a method, declare the variable as global in the method.

     

    x = 0

     

    def do_something()

         global x

         x += 1

     

    Using global variables should be avoided in most cases, especially for larger programs. For larger programs using classes and instance variables is better than using global variables, but you can get away with using global variables for small programs.