New classes in 2.2

Syver Enstad syver-en+usenet at online.no
Sat Apr 6 15:23:32 EST 2002


I have to admit that I am excited about the revisions to pythons
object model. I hope that the current state of affairs where there are
two kinds of classes will eventually fade away, as it seems quite ugly
at the time being (wouldn't want to be a new to Python just now). It
would be sad if Python we're to develop along the lines as C++, where
there seems to be no obvious way to do even the simplest of things (in
my view, even though I think it's a fascinating language, my main
language in fact until I discovered Python).

I've started looking more closely at the new style classes (object
derived). And it struck me as strange that in Guido's Unifying types
and classes in Python 2.2, the new super function and proper
classmethods are discussed. I soon found out that super would (in
addition to ordinary methods) only work for class data members and
static functions, and not for class methods were they in my view would
be most elegant.

I am sure someone has got a better version of super for class methods
than I can present here, but I insert it below anyway as a motivation
to improve or post a link to a better implementation. 

(Shamelessly stolen from guido's Super class in his article, and
blindly hacked till it did what I wanted it to do then and there :-):

class ClassMethodSuper(cls):
    def __init__(self, cls):
        self.__cls__ = cls
    def __getattr__(self, attr):
        starttype = self.__cls__
        mro = iter(starttype.__mro__)
        for cls in mro:
            if cls is self.__cls__:
                break
        for cls in mro:
            if attr in cls.__dict__:
                x = getattr(cls, attr)
                x = Command(x.im_func, self.__cls__)
                return x
        raise AttributeError, attr


class Command(object):
    def __init__(self, func, *args, **kwargs):
        self.func = func
        self.args = args
        self.kw = kwargs

    def __call__(self, *args, **kwargs):
        args = self.args + args
        kwargs.update(self.kw)
        self.func(*args, **kwargs)


-- 

Vennlig hilsen 

Syver Enstad



More information about the Python-list mailing list