how do I properly inherit from a superclass that has a __new__ method?

后端 未结 3 682
我寻月下人不归
我寻月下人不归 2021-01-11 17:55

Let\'s assume we have a class \'Parent\' , that for some reason has __new__ defined and a class \'Child\' that inherits from it. (In my case I\'m trying to inh

3条回答
  •  囚心锁ツ
    2021-01-11 18:55

    As I understand it, when you call Child("myarg", "otherarg"), that actually means something like this:

    c = Child.__new__(Child, "myarg", "otherarg")
    if isinstance(c, Child):
        c.__init__("myarg", "otherarg")
    

    You could:

    1. Write an alternative constructor, like Child.create_with_extra_arg("myarg", "otherarg"), which instantiates Child("otherarg") before doing whatever else it needs to.

    2. Override Child.__new__, something like this:

    .

    def __new__(cls, myarg, argforsuperclass):
        c = Parent.__new__(cls, argforsuperclass)
        c.field = myarg
        return c
    

    I haven't tested that. Overriding __new__ can quickly get confusing, so it's best to avoid it if possible.

提交回复
热议问题