Inherit Class Dynamicly
Laura Creighton
lac at strakt.com
Wed Feb 6 07:15:05 EST 2002
I was really tired when I posted that article yesterday and misunderstood
what you wanted. Apologies. I think that this will be more to your liking:
> > Hi, everybody,
> >
> > 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?
> >
> > Thanks from
> >
> > Xiao-Qin
> >
from __future__ import nested_scopes
import Tkinter
class WrappedWidget:
def __init__(self, frame, widgetType=Tkinter.Label, **kw):
self._widget=widgetType(frame, **kw)
self.bind("<ButtonPress-1>", self.gotPressed)
def __getattr__(self, name):
if name.startswith("__") and name.endswith("__"):
raise AttributeError, name
else:
return getattr(self._widget, name)
def gotPressed(self, event):
print 'I got Pressed!'
self.configure(bg='red')
###########################
if __name__ == '__main__':
root = Tkinter.Tk()
quit = Tkinter.Button(root, text="QUIT", fg="red", command=root.quit)
quit.pack(side='left')
Lab=WrappedWidget(root, fg='green', text='Label (default)')
Lab.pack(side='left', fill='both', expand = 1)
mydict={'fg':'yellow', 'text':'Button'}
But=WrappedWidget(root, Tkinter.Button, **mydict)
But.pack(side='left', fill='both', expand = 1)
root.mainloop()
--------------------------------------------
This is the decorator pattern. Boy is it simple in python.
Note, this relies on the behaviour of classic classes, where you search
all the methods in a class _first_, and then if it is not found, you
use the redefined __getattr__. In 2.2 in new style classes, the
__getattr__ is looked up _first_ so this will not work. I haven't
figured out how to make the decorator pattern in 2.2 not classic
patterns yet.
Sorry to have posted half asleep last night.
Laura Creighton
More information about the Python-list
mailing list