0

Assume that I have a class ClassName which contains a method Met inside its body. Also there is a global variable var that is needed in Met.

var=1
class ClassName():
    def __init__(self):
       # ...
    #some other methods that do not need global variable here

    def Met():
        #do some other stuff that needs the global var 

Which (if any) of the forms below are correct/better?

""" Approach one """
var=1
class ClassName():
    def __init__(self):
       # ...
    #some other methods that do not need global variable here
    def Met():
        # needs the global var to operate
        global var
        # do some stuff with var (including editing) 


""" Approach two"""
var=1
class ClassName(var):
    def __init__(self):
       # ...
    #some methods that do not need global variable here
    def Met(var):
        # do some stuff with var (including editing) 

PS

I have updated my question. Now my question concerns the class and method instead of functions within a function (which is not common nor recommanded).

arash
  • 161
  • 13
  • This question is basically (before and after the edit) about the usage of global variables. See my answer for some reasons why global variables should usually be avoided. – Axel Apr 17 '18 at 14:40

2 Answers2

0

I would always prefer method 2, to prevent possible misuse of global variables. In general I would try to avoid the use of global variables as much as possible, as there is always a risk in larger projects that you might redefine or assign values by mistake.

You can read more about scoping rules in Python in this answer.

Some more reasons why global variables are evil and should be avoided, can be found in this answer.

EDIT: After your edit I would still advise to try to avoid global variables, which your question boils down to.

Axel
  • 1,415
  • 1
  • 16
  • 40
0

When you do the following:

var=1
def func1():
    #do some stuff
    #do not need global variable here

    def func2():
        #do some other stuff
        # need the global var

    func2() # call func2

var is already a global variable. You can simply choose not to use it outside func2 if you don't want. You don't need to explicitly declare it as global inside func2 again as you do in Method 1. One reason to prefer Method 2 is if you expect var to change or get reassigned.

In general, you may want to also avoid nesting functions. More details on that in this answer.