dimanche 1 octobre 2017

Python interface and self instanciation

I have a question of a more design nature regarding a simple strategy design pattern.

Lets say I have an interface:

class RenewInterface:
    def __init__(*args, **kwargs):
        self.var1 = {}
        self.var2 = []
        if args:
            for i in args:
                inst = i()
                self.var1[inst.__class__.__name__] = inst

    @abstractmethod
    def renew(*args, **kwargs)
        Do some stuff and call renew in self.var1[inst__class__.__name__]

class ChildClass(RenewInterface):
    def __init__(*args, **kwargs):
        super(ChildClass, self).__init__(*args, **kwargs)

    def renew(self, *args, **kwargs)
        Do more stuff

When I inherit from that class and if i choose to call the superclass __init__ (the above code). If i have no args then I will only expose the var1 and var2 to the child class, but if I for some reason had args and i called the parent(RenewInterface) with super(ChildClass,self).__init__(*args, **kwargs) and the arg for some reason was a string class of self(ChildClass), then I guess I would instanciate the ChildClass from itself? Since I don't care about the variables in the superclass is OK to:

  1. Skip calling the superclass
  2. Skip the __init__ all together in the ChildClass?, but then it uses the RenewInterface __init__ again for instanciation

I've tried it all and it all works, but I'm not sure what the most "pythonic" way of doing it is? Or more importantly does this vary from version 2.6, 2.7 and python>=3.3.

I've read the docs, and tried google, but I have not found any conclusive information :(

Regards

Aucun commentaire:

Enregistrer un commentaire