The __new__ () function can only be used for modern classes that inherit from object.
First look at the definition of the __new__ () method in the object class:
class
object
:
@staticmethod
# known case of __new__
def
__new__(
cls
,
*
more):
# known special case of object.__new__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
Object defines the __new__ () method as a static method and requires at least one parameter cls,cls to represent the class that needs to be instantiated, which is automatically provided by the Python interpreter when instantiated.
Let's look at the implementation of the __NEW__ () method in the following class:
class
Demo(
object
):
def
__init__(
self
):
print
‘__init__() called...‘
def
__new__(
cls
,
*
args,
*
*
kwargs):
print
‘__new__() - {cls}‘
.
format
(
cls
=
cls
)
return
object
.__new__(
cls
,
*
args,
*
*
kwargs)
if
__name__
=
=
‘__main__‘
:
de
=
Demo()
Output:
__new__()
-
<
class
‘__main__.Demo‘
>
__init__() called...
When the object is instantiated, the __new__ () method is called before the call to __init__ () is initialized.
__new__ () must have a return value that returns an instantiated instance, and it is important to note that you can return an instance of the parent class __new__ (), or you can directly back an instance of Object __new__ ().
__init__ () has a parameter, self, which is the instance returned by __new__ (), and __init__ () can perform some other initialization action on the basis of __new__ (), and __init__ () does not need a return value.
If __new__ () does not correctly return an instance of the current class CLS, then __init__ () will not be called, even if it is an instance of the parent class.
We can compare the class to the manufacturer, the __new__ () method is the pre-purchase of raw materials, __init__ () method is on the basis of raw materials, processing, the initialization of commodity links.
In the actual application process, we can use this:
class
LxmlDocument(object_ref):
cache
=
weakref.WeakKeyDictionary()
__slots__
=
[
‘__weakref__‘
]
def
__new__(
cls
, response, parser
=
etree.HTMLParser):
cache
=
cls
.cache.setdefault(response, {})
if
parser
not
in
cache:
obj
=
object_ref.__new__(
cls
)
cache[parser]
=
_factory(response, parser)
return
cache[parser]
The use of the __new__ () method in this class is to check for the presence of the object in the cache before initializing it, to return the cached object directly if it exists, and to put the object in the cache for the next use if it does not exist.
In a single example, a single example can be implemented by overloading __new__:
Class Singleton (object): def __new__ (CLS, *args, **kwargs): If not hasattr (CLS, ' _instance '): cls._ Instance = Super (Singleton, CLS). __new__ (CLS, *args, **kwargs) return Cls._instanc
Use of the __new__ () method in Python