`__init__` 能做什么而 `__new__` 不能?

2023-09-02Python开发问题
1

本文介绍了`__init__` 能做什么而 `__new__` 不能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 Python 中,__new__ 用于初始化不可变类型,__init__ 通常用于初始化可变类型.如果 __init__ 从语言中删除,什么不能再做(容易)?

In Python, __new__ is used to initialize immutable types and __init__ typically initializes mutable types. If __init__ were removed from the language, what could no longer be done (easily)?

例如,

class A:

    def __init__(self, *, x, **kwargs):
        super().__init__(**kwargs)
        self.x = x


class B(A):

    def __init__(self, y=2, **kwargs):
        super().__init__(**kwargs)
        self.y = y

可以像这样使用 __new__ 重写:

Could be rewritten using __new__ like this:

class A_N:

    def __new__(cls, *, x, **kwargs):
        obj = super().__new__(cls, **kwargs)
        obj.x = x
        return obj


class B_N(A_N):

    def __new__(cls, y=2, **kwargs):
        obj = super().__new__(cls, **kwargs)
        obj.y = y
        return obj

<小时>

澄清问题范围:这不是关于如何使用 __init____new__ 或它们之间有什么区别的问题.这是一个关于如果从语言中删除 __init__ 会发生什么的问题.有什么会坏吗?有什么事情会变得更难或不可能吗?


Clarification for scope of question: This is not a question about how __init__ and __new__ are used or what is the difference between them. This is a question about what would happen if __init__ were removed from the language. Would anything break? Would anything become a lot harder or impossible to do?

推荐答案

你可以在 __init__ 中做的所有事情,也可以在 __new__ 中完成.

Everything you can do in __init__ can also be done in __new__.

那么,为什么要使用 __init__?
因为您不必将实例存储在变量中(示例代码中的 obj ),然后再费心返回它.你可以专注于你真正想做的事 –初始化可变对象.

Then, why use __init__?
Because you don't have to store instance in variable (obj in your example code), and later bother returning it. You can focus on what you realy want to do – initializing mutable object.

这篇关于`__init__` 能做什么而 `__new__` 不能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10