Return new object from __new__ method

Imagine I have a the class shown below:

class Test(object):
    def __new__(cls, greet: str) -> object:
        obj = object.__init__(cls)
        return obj

I would like to know if the above code is proper for returning a new object?

No, because __init__ is not going to construct a new object. Generally, when you write a dunder method, you’re going to be calling the same dunder method on the parent. Something like this will work:

def __new__(cls):
    obj = object.__new__(cls)
    return obj

However, this doesn’t give any advantage over simply omitting the __new__ method altogether. Generally, if you’re overriding new, it’s because you want to NOT construct additional objects; for example:

class Bool:
    def __new__(cls, obj):
        if obj: return True
        return False

or at very least, only construct them sometimes:

class Pylon:
    cache = []
    def __new__(cls):
        if cls.num_needed > len(cls.cache):
            # you must construct additional Pylons
        return random.choice(cls.cache)

But generally speaking, it’s object.__new__ that will actually make you a new object.

1 Like

@Rosuav okay, thank you. That makes a lot of sense.