GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||
GeezerVison is showing zetcode.com — Python __new__ Method - Complete Guide Python __new__ Methodlast modified March 25, 2025
This comprehensive guide explores Python's Understanding __new__ Basics
The basic_new.py
class Example:
def __new__(cls, *args, **kwargs):
print("__new__ called")
instance = super().__new__(cls)
return instance
def __init__(self, value):
print("__init__ called")
self.value = value
obj = Example(10)
In this basic example, we see the order of operations when creating an
object. The
Key characteristics of
Customizing Object Creation
The custom_creation.py
class CustomObject:
def __new__(cls, value):
if value < 0:
return None # Return None for negative values
instance = super().__new__(cls)
instance.created_at = time.time()
return instance
def __init__(self, value):
self.value = value
obj1 = CustomObject(5) # Creates instance
obj2 = CustomObject(-1) # Returns None
This example demonstrates several important concepts:
Practical applications include:
Implementing the Singleton PatternThe singleton.py
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance.initialized = False
return cls._instance
def __init__(self):
if not self.initialized:
print("Initializing Singleton")
self.initialized = True
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # True
This implementation guarantees only one instance exists by:
Important considerations:
Creating Immutable Objects
immutable.py
class ImmutablePoint:
__slots__ = ('x', 'y') # Prevents dynamic attribute creation
def __new__(cls, x, y):
instance = super().__new__(cls)
instance.x = x # Allowed during creation
instance.y = y
return instance
def __setattr__(self, name, value):
raise AttributeError(f"Cannot modify {name}")
p = ImmutablePoint(3, 4)
print(p.x, p.y) # Works
p.x = 5 # Raises AttributeError
This immutable implementation combines several techniques:
Why this works:
Subclassing Built-in Types
subclass_tuple.py
class NamedTuple(tuple):
def __new__(cls, items, name):
instance = super().__new__(cls, items)
instance.name = name
return instance
def __init__(self, items, name):
# __init__ is still called but often unused in these cases
pass
nt = NamedTuple([1, 2, 3], "My Numbers")
print(nt) # (1, 2, 3)
print(nt.name) # "My Numbers"
When subclassing immutable types:
Common use cases:
Object Pooling Pattern
object_pool.py
class DatabaseConnection:
_pool = {}
_max_pool_size = 3
def __new__(cls, connection_string):
if connection_string not in cls._pool:
if len(cls._pool) >= cls._max_pool_size:
raise RuntimeError("Connection pool exhausted")
instance = super().__new__(cls)
instance._connect(connection_string)
cls._pool[connection_string] = instance
return cls._pool[connection_string]
def _connect(self, connection_string):
print(f"Connecting to {connection_string}")
self.connection_string = connection_string
conn1 = DatabaseConnection("db1.example.com")
conn2 = DatabaseConnection("db1.example.com") # Returns same instance
This object pool implementation:
Benefits of object pooling:
Metaclass __new__ Method
In metaclasses, meta_new.py
class MetaLogger(type):
def __new__(mcls, name, bases, namespace):
print(f"Creating class {name}")
# Add a class-level logger
namespace['logger'] = logging.getLogger(name)
return super().__new__(mcls, name, bases, namespace)
class User(metaclass=MetaLogger):
pass
print(User.logger) #
Metaclass
Common metaclass uses:
Best Practices and PitfallsWhen working with
Conclusion
The
Use it judiciously when you need precise control over instance creation, but
prefer Source ReferencesAuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. List all Python tutorials. | ||||||||
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |