[Tutor] global variables/constants versus volatile variables/constants

Steven D'Aprano steve at pearwood.info
Sat Jun 14 21:33:05 CEST 2014


On Sat, Jun 14, 2014 at 06:23:08PM +0530, diliup gabadamudalige wrote:

> Say if I have a lot of Lists, strings and variables used to carry data to
> and from various functions why can't I have a class with all these in it? 

Of course you *can*, but you *should not*. Read on...

[...]
> so I declare
> 
> class Containers():
>     def __init__(self):
>         self.last_selected_scale= ""
>         self.scale_notes = ""
>         self.arpeggionotes = ""
etc.

> now i initiate the class with
> v=Containers()

So now you write code where everything you use starts with "v.". What 
does the v. do? How does it help your programming?

Answer: it doesn't. It just makes an extra two characters to type. 
Compare the code you would write if you just defined the variables 
directly:

# Option 1
last_selected_scale = ""
scale_notes = ""
arpeggionotes = ""

do_something(last_selected_scale)
do_another_thing(scale_notes, arpeggionotes)


# Versus option 2:
class Containers():
    def __init__(self):
        self.last_selected_scale = ""
        self.scale_notes = ""
        self.arpeggionotes = ""

v = Container()
do_something(v.last_selected_scale)
do_another_thing(v.scale_notes, v.arpeggionotes)



The two options do *exactly* the same thing, but Option 2 takes much 
more typing and reading. For what benefit?

The only benefit is if you might have multiple Containers at the same 
time:

keyboard_a = Container()
keyboard_b = Container()

do_something(keyboard_a.last_selected_scale)
do_another_thing(keyboard_b.scale_notes, keyboard_b.arpeggionotes)


Now you can play and record with two keyboards at the same time. 
(Perhaps you have four arms? *smile*) In this case, the extra cost of 
using a class pays for itself. Otherwise, it is just wasted effort.



-- 
Steven


More information about the Tutor mailing list