Creating an Instance Without Invoking init
Problem
You need to create an instance but want to bypass the execution of
the __init__() method for some reason.
Solution
A bare uninitialized instance can be created by directly calling the
__new__() method of a class. For example, consider this class:
classDate(object):def__init__(self,year,month,day):self.year=yearself.month=monthself.day=day
Here’s how you can create a Date instance without invoking __init__():
>>>d=Date.__new__(Date)>>>d<__main__.Date object at 0x1006716d0>>>>d.yearTraceback (most recent call last):File"<stdin>", line1, in<module>AttributeError:'Date' object has no attribute 'year'>>>
As you can see, the resulting instance is uninitialized. Thus, it is now your responsibility to set the appropriate instance variables. For example:
>>>data={'year':2012,'month':8,'day':29}>>>forkey,valueindata.items():...setattr(d,key,value)...>>>d.year2012>>>d.month8>>>
Discussion
The problem of bypassing __init__() sometimes arises when instances
are being created in a nonstandard way, such as when deserializing
data or in the implementation of a class method that’s been defined as
an alternate constructor. For example, on the Date class shown, someone might define an alternate constructor ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access