Skip to main content
 首页 » 编程设计

python之什么是 Python 不可变类的 __init__ 方法,例如漂浮的样子

2024年10月24日13davidwang456

看来Python不可变类的__init__方法没有意义,因为对象创建后,属性赋值是不允许的。但显然 __init__ 方法确实存在于不可变对象(immutable对象)中。它是如何实现的?它有空方法体吗?

请您参考如下方法:

__init__ 什么都不做,只是继承自 object。所有工作都在 __new__ 中完成。

In [1]: float.__init__ 
Out[1]: <slot wrapper '__init__' of 'object' objects> 
 
In [2]: float.__new__ 
Out[2]: <function float.__new__> 

float类的tp_new的定义是float_new,可见here .