[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How should we use global variables correctly?

On 2019-08-23 8:43 AM, Windson Yang wrote:
> I also want to know what is the difference between "using 'global
> variables' in a py module" and "using a variable in class". For example:
> In global.py:
>      foo = 1
>      def bar():
>          global foo
>          return foo + 1
> In class.py
>       class Example:
>          def __init__(self):
>              self.foo = 1
>          def bar()
>              return self.foo + 1
> Expect the syntax, why using class variable self.foo would be better (or
> more common)? I think the 'global' here is relative, foo is global in
> global.py and self.foo is global in Example class. If the global.py is
> short and clean enough (didn't have a lot of other class), they are pretty
> much the same. Or I missed something?

One difference is that you could have many instances of Example, each 
with its own value of 'foo', whereas with a global 'foo' there can only 
be one value of 'foo' for the module.

It would make sense to use the 'global' keyword if you have a module 
with various functions, several of which refer to 'foo', but only one of 
which changes the value of 'foo'.

Frank Millman