Python:总是使用 __new__ 而不是 __init__?

发布于 2024-09-07 11:00:26 字数 430 浏览 1 评论 0原文

我了解 __init____new__ 的工作原理。 我想知道是否有什么 __init__ 可以做 __new__ 不能做的事情?

即可以将 __init__ 的使用替换为以下模式:

class MySubclass(object):
    def __new__(cls, *args, **kwargs):
        self = super(MySubclass, cls).__new__(cls, *args, **kwargs)
        // Do __init__ stuff here
        return self

我这样问是因为我想让 Python OO 的这一方面更适合我的头脑。

I understand how both __init__ and __new__ work.
I'm wondering if there is anything __init__ can do that __new__ cannot?

i.e. can use of __init__ be replaced by the following pattern:

class MySubclass(object):
    def __new__(cls, *args, **kwargs):
        self = super(MySubclass, cls).__new__(cls, *args, **kwargs)
        // Do __init__ stuff here
        return self

I'm asking as I'd like to make this aspect of Python OO fit better in my head.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

归属感 2024-09-14 11:00:26

因此,类的类通常是 type,当您调用 Class() 时,会调用 Class< 上的 __call__() 方法。 /code> 的类处理这个问题。我相信 type.__call__() 的实现或多或少是这样的:

def __call__(cls, *args, **kwargs):
    # should do the same thing as type.__call__
    obj = cls.__new__(cls, *args, **kwargs)
    if isinstance(obj, cls):
        obj.__init__(*args, **kwargs)
    return obj

你的问题的直接答案是否定的,__init__() 可以做的事情 (change / "初始化”指定的实例)是 __new__() 可以执行的操作的子集(创建或以其他方式选择它想要的任何对象,在返回对象之前对该对象执行任何它想要的操作)。

不过,同时使用这两种方法会很方便。 __init__() 的使用更简单(它不必创建任何东西,也不必返回任何东西),我相信最好的做法是始终使用 __init__( ) 除非您有特定原因使用 __new__()

So, the class of a class is typically type, and when you call Class() the __call__() method on Class's class handles that. I believe type.__call__() is implemented more or less like this:

def __call__(cls, *args, **kwargs):
    # should do the same thing as type.__call__
    obj = cls.__new__(cls, *args, **kwargs)
    if isinstance(obj, cls):
        obj.__init__(*args, **kwargs)
    return obj

The direct answer to your question is no, the things that __init__() can do (change / "initialize" a specified instance) is a subset of the things that __new__() can do (create or otherwise select whatever object it wants, do anything to that object it wants before the object is returned).

It's convenient to have both methods to use, however. The use of __init__() is simpler (it doesn't have to create anything, it doesn't have to return anything), and I believe it is best practice to always use __init__() unless you have a specific reason to use __new__().

静赏你的温柔 2024-09-14 11:00:26

guido 的帖子(感谢@fraca7):

例如,在pickle模块中,__new__用于在反序列化对象时创建实例。在这种情况下,会创建实例,但不会调用 __init__ 方法。

还有其他类似的答案吗?


我接受这个答案作为对我自己的问题的“是”:

我想知道是否有什么 __init__ 可以做 __new__ 不能做的事情?

是的,与 __new__ 不同,您在 __init__ 方法中放入的操作不会在 unpickle 过程中执行。 __new__ 无法做出这种区分。

One possible answer from guido's post (thanks @fraca7):

For example, in the pickle module, __new__ is used to create instances when unserializing objects. In this case, instances are created, but the __init__ method is not invoked.

Any other similar answers?


I'm accepting this answer as a 'yes' to my own question:

I'm wondering if there is anything __init__ can do that __new__ cannot?

Yes, unlike __new__, actions that you put in the __init__ method will not be performed during the unpickling process. __new__ cannot make this distinction.

神回复 2024-09-14 11:00:26

好吧,在谷歌上寻找 __new__ vs __init__ 向我展示了

长话短说,__new__返回一个新的对象实例,而__init__不返回任何内容,只是初始化类成员。

编辑:要真正回答您的问题,您永远不需要重写 __new__ ,除非您要子类化不可变类型。

Well, looking for __new__ vs __init__ on google showed me this.

Long story short, __new__ returns a new object instance, while __init__ returns nothing and just initializes class members.

EDIT: To actually answer your question, you should never need to override __new__ unless you are subclassing immutable types.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文