lundi 28 mai 2018

Python: how to implement copy for base class which works for inherited with new attributes

How to implement copy for base class which works for inherited with new attributes w/o implementing __copy__ for inherited class (implying dumb copy for new attributes)?

I.e. we have class with one user-defined and one calculated (or external reference, should not be copied) fields. So copy should create instance, based only on user-defined field:

class A(object):
    def __init__(self, a):
        self.a = a
        self.b = a+1

    def __copy__(self):
        return A(self.a)

At this moment copy works fine.

Then we introduce inherited class, and it's constructor calculates args for base constructor based on it's own args, and also introduce new field, so signature of inherited constructor is completely different and unknown (in common) for base class:

class B(A):
    def __init__(self, c):
        A.__init__(self, c+100)
        self.c=c

At this moment copy obviously works not fine, returning A instance. Of cause we can implement own __copy__ for inherited class, but it's extremely inconvenient, when we introduce some attributes, which should be copied in just ordinary manner. So what I'd like to achieve, is to copy "A part" of inherited class B by A.__copy__, but remains by standard copy, w/o re-implementing __copy__ for all inherited classes. So are there any 'design pattern' for such situations?

Aucun commentaire:

Enregistrer un commentaire