Inherit Class Dynamicly

Eric Brunel eric.brunel at pragmadev.com
Tue Feb 5 09:34:04 EST 2002


Hi Xiao-Qin Xia,

> from Tkinter import *
> class NewWidget:
>         ...
>         def __init__(self, widget_name = "Button", **dict):
>                 # What is needed here to make the new born object(self)
>                 # behavior like both the class specified by widget_name
>                 # and NewWidget?

I'd do something like:

import Tkinter  # Simpler here than "from Tkinter import *"
class NewWidget:
        def __init__(self, widget_name = "Button", **dict):
                tkClass = getattr(Tkinter, widget_name)
                self.__actualWidget = tkClass( ... whatever ...)
        def __getattr__(self, attrName):
                return getattr(self.__actualWidget, attrName)

The attribute __actualWidget will contain an instance of the Tkinter class 
with the name passed to the constructor, and the __getattr__ method will 
ensure that all unknown attributes or methods in the NewWidget class are 
delegated to the Tkinter object. A kind of specilization by delegation 
instead of the usual one done by inheritance. You may also need a 
__setattr__ method in your NewWidget class.

But be warned: specializing Tkinter classes (like above or the usual way) 
may not have the result you expect since many things are "hardcoded" within 
Tk. Many methods available in Python are never actually called internally 
by Tk. For example, if you have a sub-class of StringVar overloading the 
"set" method, your method will never be called on user input.

Anyway, HTH
 - eric -



More information about the Python-list mailing list