假设以下代码:
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
类中:
它从不打印“initialization”,即使__init__
应该在__new__
之后调用,因为__new__
返回了对象的实例,不是吗?如果不是,那我是在搞什么?在
不,python不需要
__init__
,但是如果只有__new__
,那么每次创建一个类时,都需要计算出进入__new__
的所有位和部分。在它使python更容易分离出这两者,而且不容易出错。在
另外,历史上
__init__
先于__new__
。在__init__
排在第一位。__new__
主要添加到。。。好吧,我让documentation解释一下:__init__
对于旧样式的类系统来说已经足够好了。即使您子类化了一个“不可变”的旧样式类,也只需为超类的__init__
提供适当的参数。这不能用子类,比如,tuple
来剪切它。在至于
__init__
没有被调用:相关问题 更多 >
编程相关推荐