Using a class' __new__ method as a Factory: __init__ gets called twice

前端 未结 3 1718
南旧
南旧 2020-12-04 19:15

I encountered a strange bug in python where using the __new__ method of a class as a factory would lead to the __init__ method of the instantiated

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 20:07

    I can't actually reproduce this behavior in either of the Python interpreters I have installed, so this is something of a guess. However...

    __init__ is being called twice because you are initializing two objects: the original Shape object, and then one of its subclasess. If you change your __init__ so it also prints the class of the object being initialized, you will see this.

    print type(self), "init called"
    

    This is harmless because the original Shape will be discarded, since you are not returning a reference to it in your __new__().

    Since calling a function is syntactically identical to instantiating a class, you can change this to a function without changing anything else, and I recommend that you do exactly that. I don't understand your reluctance.

提交回复
热议问题