为什么不在python中只使用\uuyou new_优,而不使用\uunew_uu和\uuuu init_u?

2024-10-03 21:28:52 发布

您现在位置:Python中文网/ 问答频道 /正文

假设以下代码:

class NumStorage(object):

    def __new__(cls, *nargs):
        name = cls.__name__
        parents = cls.__bases__
        kwargs = {'num%i' % pos : i for pos, i in enumerate(nargs, 1)}
        if any(kwargs.values()) and len(kwargs.values()) >= 2:
            end = len(kwargs.values()) + 1
            kwargs['num%i' % end] = sum(kwargs.values())
        self = type(name, parents, kwargs)
        return self

这个NumStorage对象接受任意数量的数字,如果有两个或更多个数字,并且它们的总和加起来大于0,那么它将创建一个新的kwarg键。在

如果NumStorage实例的初始化可以在__new__中发生,那么python到底为什么还需要一个__init__?另一件让我困惑的事情是,如果我们真的将__init__方法添加到NumStorage类中:

^{pr2}$

它从不打印“initialization”,即使__init__应该在__new__之后调用,因为__new__返回了对象的实例,不是吗?如果不是,那我是在搞什么?在


Tags: 对象nameposselfnewleninit数字
2条回答

does python even need an __init__?

不,python不需要__init__,但是如果只有__new__,那么每次创建一个类时,都需要计算出进入__new__的所有位和部分。在

它使python更容易分离出这两者,而且不容易出错。在

另外,历史上__init__先于__new__。在

__init__排在第一位。__new__主要添加到。。。好吧,我让documentation解释一下:

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

__init__对于旧样式的类系统来说已经足够好了。即使您子类化了一个“不可变”的旧样式类,也只需为超类的__init__提供适当的参数。这不能用子类,比如,tuple来剪切它。在

至于__init__没有被调用:

If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().

If __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.

相关问题 更多 >