Content · Programming · Python

Python __new__() vs __init__(): Object Creation

Separate allocation in __new__() from initialization in __init__().

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Separate allocation in __new__() from initialization in __init__().

How It Works


__new__(cls, ...) creates and returns an instance; __init__(self, ...) configures an instance when appropriate. Most classes only need __init__; custom immutable subclasses may use __new__.

Be especially careful when customizing immutable built-in types.

Step-by-Step Example


class UppercaseString(str):
    def __new__(cls, value):
        return super().__new__(cls, value.upper())

converted_value = UppercaseString("python")
print(converted_value)
print(isinstance(converted_value, str))

Understanding the Example


  • The class groups related state and methods so each instance can manage its own values.
  • The function definition gives the operation a reusable name and makes its inputs explicit.

A successful run of this example prints the following output:

PYTHON
True

Where This Fits in a Real Program


A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.

Practice: Try It Yourself


Create a str subclass that strips surrounding whitespace on construction.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Returning a non-instance from __new__ and expecting __init__ to run normally.
  • Adding unnecessary __new__ overrides for ordinary mutable classes.

Key Takeaways


  • Separate allocation in __new__() from initialization in __init__().
  • __new__(cls, ...) creates and returns an instance; __init__(self, ...) configures an instance when appropriate.
  • Be especially careful when customizing immutable built-in types.
Share this resourceSend this page to someone who may find it useful.