Sub topic 3
Creating objects: __new__ and __init__
This chapter assumes you can define classes, write instance methods, and know that __init__ sets up attributes. You will learn what happens before __init__ runs and when __new__ is worth writing.
Two steps, not one
Calling a class, such as Vector(1, 2), runs two special methods in order:
__new__(cls, ...)creates the object and returns it.__init__(self, ...)receives that object and sets it up.
__new__ is a static method that Python treats specially. It gets the class as its first argument. If it returns an instance of cls, Python then calls __init__ on that instance with the same arguments. If it returns anything else, __init__ is skipped.
You can watch the order with prints:
class Demo:
def __new__(cls, *args, **kwargs):
print('__new__', args)
return super().__new__(cls)
def __init__(self, value):
print('__init__', value)
self.value = value
d = Demo(42)
# __new__ (42,)
# __init__ 42Note that super().__new__(cls) is called without the extra arguments. object.__new__ rejects extra arguments when you override __new__, so pass only cls.
When you need `__new__`
Most classes only need __init__. Write __new__ when the object must be shaped before it exists, which usually means one of these cases:
- Subclassing an immutable built-in such as
int,strortuple. Their values are fixed at creation, so changing them in__init__is too late. - Controlling instance creation, for example reusing one instance (a singleton) or caching instances.
Here is an immutable subclass. The value is adjusted in __new__:
class Percent(float):
def __new__(cls, value):
clamped = max(0.0, min(100.0, value))
return super().__new__(cls, clamped)
print(Percent(150)) # 100.0
print(Percent(-5)) # 0.0
print(Percent(42.5)) # 42.5A singleton shows the second case:
class Config:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
print('init called')
a = Config()
b = Config()
print(a is b) # TrueCommon errors
- Returning a value from
__init__. It must returnNone. Returning anything else raisesTypeError. - Forgetting
returnin__new__. The call then evaluates toNone, and__init__never runs. - Passing extra arguments to
object.__new__. This raisesTypeErrorwhen__new__is overridden. Callsuper().__new__(cls)and handle the arguments yourself. - Assuming
__new__and__init__have different signatures. Both receive the arguments passed to the class call, so accept the same parameters or use*args, **kwargs.
Exercise
A class Name(str) should always store its text in lowercase. Why does putting the conversion in __init__ not work, and where should it go?
Show answer
A str is immutable and its value is fixed when the object is created, so assigning in __init__ cannot change it. Put the conversion in __new__: def __new__(cls, text): return super().__new__(cls, text.lower()).
Exercise
In what order do __new__ and __init__ run, and when is __init__ skipped?
Show answer
__new__ runs first and creates the object. __init__ runs second on that object. __init__ is skipped when __new__ returns something that is not an instance of the class.