why defined '__new__' and '__init__' all in a class

前端 未结 4 809
轻奢々
轻奢々 2020-12-24 03:39

i think you can defined either \'__init__\' or \'__new__\' in a class,but why all defined in django.utils.datastructures.py.

my code:

4条回答
  •  不思量自难忘°
    2020-12-24 04:17

    __new__ and __init__ do completely different things. The method __init__ initiates a new instance of a class --- it is a constructor. __new__ is a far more subtle thing --- it can change arguments and, in fact, the class of the initiated object. For example, the following code:

    class Meters(object):
        def __new__(cls, value):
            return int(value / 3.28083)
    

    If you call Meters(6) you will not actually create an instance of Meters, but an instance of int. You might wonder why this is useful; it is actually crucial to metaclasses, an admittedly obscure (but powerful) feature.

    You'll note that in Python 2.x, only classes inheriting from object can take advantage of __new__, as you code above shows.

    The use of __new__ you showed in django seems to be an attempt to keep a sane method resolution order on SortedDict objects. I will admit, though, that it is often hard to tell why __new__ is necessary. Standard Python style suggests that it not be used unless necessary (as always, better class design is the tool you turn to first).

提交回复
热议问题