Skip to content

Instantly share code, notes, and snippets.

@WazedKhan
Created June 20, 2024 02:36
Show Gist options
  • Select an option

  • Save WazedKhan/291ae0ee003ce42109bf049fe347e503 to your computer and use it in GitHub Desktop.

Select an option

Save WazedKhan/291ae0ee003ce42109bf049fe347e503 to your computer and use it in GitHub Desktop.

The new method in Python is a fundamental method that is responsible for creating instances of a class. It is often referred to as a "static" method, although technically it's a class method because Python implicitly passes the class (cls) as the first argument.

Purpose of __ new __

The primary role of __ new __ is to create and return a new instance of a class. It is called before __ init __, which initializes the created instance. Here’s a step-by-step breakdown:

  1. Class Creation: When we write a class and create an instance of it, Python internally calls __ new __ to create the object.

  2. Instance Initialization: After __ new __ creates the instance, Python then calls __ init __ to initialize it.

Basic Usage

class MyClass:
    def __new__(cls, *args, **kwargs):
        # Custom object creation logic goes here
        instance = super().__new__(cls)
        # Additional initialization can be done here if needed
        return instance
    
    def __init__(self, *args, **kwargs):
        # Instance initialization code goes here
        pass

# Creating an instance of MyClass
obj = MyClass()

Explanation

  • __ new __ Method:

    • Parameters: __ new __ accepts the class (cls) as the first parameter, followed by any additional arguments (*args) and keyword arguments (**kwargs).
    • Customization: we can override __ new __ to customize how instances of our class are created. This could involve creating the instance using a different method or adding additional attributes.
    • Return Value: __ new __ should return an instance of the class (cls). Typically, we create the instance using super().__ new __(cls) to invoke the parent class's __ new __ method.
  • __ init __ Method:

    • Initialization: __ init __ initializes the instance after it has been created by __ new __. It's where we typically set up initial attributes and perform any other initialization tasks.

Example Scenario

Let's say we have a class Person where we want to ensure that every person's name is capitalized when the instance is created:

class Person:
    def __new__(cls, name):
        # Ensure name is capitalized
        capitalized_name = name.capitalize()
        instance = super().__new__(cls)
        instance.name = capitalized_name
        return instance
    
    def __init__(self, name):
        # Initialization can be done here, if needed
        pass

# Creating instances
person1 = Person("Wajed")
person2 = Person("Tintin")

print(person1.name)  # Output: Wajed
print(person2.name)  # Output: Tintin

Key Points

  • Control over Instance Creation: __ new __ provides control over how instances are created. This is useful for customizing object creation logic or enforcing constraints.

  • Static/Class Method: Even though it's commonly referred to as static due to its usage pattern, technically it's a class method because Python passes the class (cls) implicitly.

  • Usage: While __ init __ is where we typically initialize instance attributes, __ new __ allows for more advanced customization of instance creation, making it powerful for handling special cases or enforcing specific behaviors during object instantiation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment