can i define a new method at runtime?

Hung Jung Lu hungjunglu at yahoo.com
Sun Jun 20 12:27:54 EDT 2004


Ville Vainio <ville at spammers.com> wrote:
> If there is a change method, I assume you need to implement the class
> yourself. Why not just subclass the root TextBox class and create a
> IntegerTextBox class that has verifyInteger in the change method? Then
> you just choose at instantiation time that this particular textbox
> needs an integer...

This is OK if there are only a few types of boxes. But entry data
types are features, and they tend to grow and become complicated, even
if Regex (regular expression) patterns were used. Besides, the
verification logic is a conceptual unit on its own right, so according
to the AOP (aspect-oriented programming) philosophy, it's best to
group the verification methods together in some "aspect class". There
may be new dimensions to the problem that one may not have foreseen at
the time of design. For instance, localization (currency, dates, usage
of commas and periods, ZIP codes, etc.) Having verification code in
its own hierarchy allows you to make changes more easily and take
advantage of class inheritance for code re-use. Once you have the
verification logic done, you hook it to the widget objects somehow. In
Python, this usually involves some form of metaprogramming. There are
too many ways to do it, and you'll probably not find two people doing
it the same way. Some tools in the arsenal are: using
functions/methods as first class objects and assign them or tweak them
to your heart's content, using the "new" module, using code objects
and "exec" statements, tweaking an existing object's __class__
attribute, implementing/overriding the __getattr__() method in
classes, metaclasses, etc. etc.

regards,

Hung Jung



More information about the Python-list mailing list