Code design for a sub-class of built-ins
Alex Martelli
aleax at mac.com
Tue Jul 4 19:41:38 EDT 2006
Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote:
...
> The obvious problem is, I have to create a custom method for every string
> method -- and if strings gain any new methods in some future version of
> Python, my subclass won't exhibit the correct behaviour.
As others already suggested, automating such decoration is pretty easy;
you can do it with either a custom metaclass or a simple post-processing
of your class in a loop. Untested details below, but the general idea
would be something like:
class SDAstr(str):
magic = 'whatever'
def _SDAdecorate(methodname, strmethod):
def decorated(self, *a, **k):
if self == self.magic: print "whatever!"
return strmethod(self, *a, **k)
setattr(SDAstr, methodname, decorated)
for methodname, strmethod in \
inspect.getmembers(str, inspect.ismethoddescriptor):
_SDAdecorate(methodname, strmethod)
and variants thereof (to provide more accurate metainformation with the
decorated methods -- name, docstring, signature, whatever; and/or to
encapsulate things in a custom metaclass; whatever).
> class MyInt(int):
> """Like an int but with special behaviour."""
> def __init__(self, value, extra):
...
> Looks like my __init__ isn't even being called here. Why not, and how do I
> fix this?
Override __new__, which is what invariably gets called (before __init__,
which only gets called if __new__ returns an instance of the class that
you're instantiating).
Alex
More information about the Python-list
mailing list