Python:总是使用 __new__ 而不是 __init__?
我了解 __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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因此,类的类通常是
type
,当您调用Class()
时,会调用Class< 上的
__call__()
方法。 /code> 的类处理这个问题。我相信type.__call__()
的实现或多或少是这样的:你的问题的直接答案是否定的,
__init__()
可以做的事情 (change / "初始化”指定的实例)是 __new__() 可以执行的操作的子集(创建或以其他方式选择它想要的任何对象,在返回对象之前对该对象执行任何它想要的操作)。不过,同时使用这两种方法会很方便。
__init__()
的使用更简单(它不必创建任何东西,也不必返回任何东西),我相信最好的做法是始终使用__init__( )
除非您有特定原因使用__new__()
。So, the class of a class is typically
type
, and when you callClass()
the__call__()
method onClass
's class handles that. I believetype.__call__()
is implemented more or less like this: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__()
.guido 的帖子(感谢@fraca7):
还有其他类似的答案吗?
我接受这个答案作为对我自己的问题的“是”:
是的,与
__new__
不同,您在__init__
方法中放入的操作不会在 unpickle 过程中执行。__new__
无法做出这种区分。One possible answer from guido's post (thanks @fraca7):
Any other similar answers?
I'm accepting this answer as a 'yes' to my own question:
Yes, unlike
__new__
, actions that you put in the__init__
method will not be performed during the unpickling process.__new__
cannot make this distinction.好吧,在谷歌上寻找
__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.