CONSTRUCT - Adding Functionality to the Overall System
George Sakkis
george.sakkis at gmail.com
Tue Sep 19 15:21:43 EDT 2006
Ilias Lazaridis wrote:
> I like to add a method "writeDebug(self, msg)" to all (or the most
> possible) classes in the system.
>
> How do I do this?
>
> * with new style classes
> * with old style classes
Short answer: you can't do it for builtin or extension types:
>>> list.writeDebug = lambda msg: "You'd wish"
...
TypeError: can't set attributes of built-in/extension type 'list'
Longer asnwer: Make it a function instead of a method. This function
could try to call the respective method, and as a fallback it would
have hardcoded what to do for each supported class, something like:
def writeDebug(obj, msg):
try: return obj.writeDebug(msg)
except AttributeError:
if isinstance(obj,list):
# list msg
elif isinstance(obj,tuple):
# tuple msg
...
else:
# default object msg
If you insist though that you'd rather not use functions but only
methods, tough luck; you're better off with Ruby.
George
More information about the Python-list
mailing list