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

Jack Diederich jackdied at gmail.com
Thu May 20 20:30:54 EDT 2010


On Thu, May 20, 2010 at 8:13 PM, Stef Mientki <stef.mientki at gmail.com> wrote:
> hello,
>
> This might be a strange question, but as a practical guy, I'm not searching
> for the best solution, but for a practical solution.
>
> I've a class which I've used very extensively.
> Now I want to extend that class with an action on a double click event, but
> that action is determined by the main program.
> Normally I would create an derived class and add that specific action.
> But I find it too much effort in this specific case, half of the instances
> need the extension, half of it dont.
> 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)
> Is this a valid construction ( sorry I'm not a programmer),
> or are there better ways to accomplish similar dynamic behavior ?
>

You can have two classes and then just change the class of the
instances that need it.

class A(object):
  def method1(self): pass

class B(A):
  def method2(self): pass

ob = A()
# click happens
ob.__class__ = B

-Jack



More information about the Python-list mailing list