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

How should we use global variables correctly?

Thank you all. I agreed with Frank that

> 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'.

I also found an example in cpython/lib/gettext.py, only 'textdomain
function' can change '_current_domain', other functions just refer to it.
So, it will be not evil or to use 'global' keyword correctly when there is
only one function can change its value?

Cameron Simpson <cs at cskk.id.au> ?2019?8?23??? ??3:15???

> On 23Aug2019 09:07, Frank Millman <frank at chagford.com> wrote:
> >On 2019-08-23 8:43 AM, Windson Yang wrote:
> >>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.
> But that is an _instance_ attribute. Which is actually what Windson Yang
> made.
> A class attribute is bound to the class, not an instance. The
> terminology is important.
> Cheers,
> Cameron Simpson <cs at cskk.id.au>
> --
> https://mail.python.org/mailman/listinfo/python-list