[Tutor] Query - Where to put in global variables, if needed, as a good programming practice

Steven D'Aprano steve at pearwood.info
Sat Jun 16 00:30:56 CEST 2012


spawgi at gmail.com wrote:
> Hello,
> 
> The point of good-bad-ness of global variables aside, if I needed to use
> them, which is a better place to put them.
> 1. In the __init__ function of a class? So they are available at the time
> an object is initialized or
> 2. In the actual function of the class where the variables are needed?
> Pros and Cons of either approach?

Neither of those are *global* variables.

In Python, global variables are those at the top level of the module, and are 
only global to a single module, not your entire program. If your program is a 
single module, there is no difference.

This confusion is one of the reasons that I hate the Java-ism of calling 
things-attached-to-classes-or-attributes as "variables" instead of members or 
attributes. In Python, the usual term for them is "attributes", and you can 
have class attributes shared between all instances of a class, and instance 
attributes that are specific to the instance.


class K:
     shared = "this attribute is shared"

     def __init__(self):
         self.attribute = "this one is specific to the instance"


Pros for class attributes:

+ they are shared, so all your instances see the same value

+ you can reach them directly from the class, without creating an
   instance first: K.shared works

Cons for class attributes:

- they are shared, so all your instances see the same value


Pros for instance attributes:

+ they are not shared, so all your instances don't see the same value

Cons for class attributes:

- they are not shared, so all your instances don't see the same value

- every time you create an instance, the attribute has to be created

- you can't reach them directly from the class without creating an
   instance first: K.attribute does not work





-- 
Steven


More information about the Tutor mailing list