Ugly modification of a class, can it be done better ?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu May 20 21:27:59 EDT 2010


Sorry for breaking threading, but Stef's original post has not come 
through to me.

> On Thu, May 20, 2010 at 8:13 PM, Stef Mientki <stef.mientki at gmail.com>
> wrote:

>> So I want to change the behavior of the class dynamically. I've done it
>> by adding a global variable (Base_Grid_Double_Click) in the module,
>> initial set to None,
>> but can be changed by the main program to some callback function. (see
>> the code below)

How is this supposed to work? If you have *one* global, then *every* 
instance will see the same setting. To change it dynamically, you enter a 
nightmare world of having to save the global, modify it, then restore it, 
every single time. Trust me, I've been there, this is the *worst* way of 
programming. This is why object oriented inheritance was invented, to 
escape this nonsense!

The first thing is to make the callback specific to the class, not 
global. Why does your printing code need access to the callback that 
handles double-clicking on a grid? It doesn't! So don't give it that 
access (at least, not easy access). Put the callback in the class.

class MyClass:
    callback = None
    def method(self, *args):
        if self.callback is None:
            behaviour_with_no_callback()
        else:
            behaviour_with_callback()
    

Now if you want to apply a callback to some instances, and not others, it 
is totally simple:


red = MyClass()
blue = MyClass()
red.callback = my_callback_function

and you're done.


If you have lots of instances that use the same callback? Make a subclass.

class MyDottedClass(MyClass):
    pass

red = MyClass()
blue = MyClass()
red_with_green_dots = MyDottedClass()
blue_with_green_dots = MyDottedClass()

MyDottedClass.callback = dotted_callback

And now all the dot instances will use the same callback without 
effecting the undotted instances. What to change them all to use a 
different behaviour?

MyDottedClass.callback = something_different

and now they all change, again without effecting the undotted instances.




>> Is this a valid construction ( sorry I'm not a programmer), or are
>> there better ways to accomplish similar dynamic behavior ?

Of course you're a programmer! You're writing programs, aren't you?




-- 
Steven



More information about the Python-list mailing list