Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

new style class - Python: always use __new__ instead of __init__?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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__().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...