If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?

metal metal29a at gmail.com
Thu Oct 29 20:03:50 EDT 2009


The actual situation is I'm coding with a immuable set-like datatype
XSet which supports XSet(['al']) & XSet(['ah'] = XSet(['ax'] if I
declare ax is consists of al and ah

"That" means I can't explian it very well 'cause my english...

Now I try to make some mess like this...I know it's not good to wrap
all methods...I just try to make code looks good

class MyMeta(type):
    def __init__(cls, name, bases, namespace):
        type.__init__(cls, name, bases, namespace) # needed?
        cls.wrap_methods()
    def methods(cls):
        return [k for k, v in cls.__dict__.items() if callable(v)]
    def wrap_methods(cls):
        for k in cls.methods():
            f = cls.__dict__[k]
            def g(self, *v, **k):
                rv = f(self, *v, **k)
                if rv.__class__ is cls:
                    rv = self.__class__()
                    rv.__dict__.update(self.__dict__)
                return rv
            setattr(cls, k, g)

class Parent(object):
    __metaclass__ = MyMeta # I prefer class decorator, but I'm using
Py2.5
    def some_method(self):
        return Parent()

class Child(Parent):
    pass

print Child().some_method()




More information about the Python-list mailing list