The new () method is mainly used to create a subclass custom instance of an unchangeable type (such as int, str, or tuples. You can also override the custom meta class to create a custom class.
object.
new
(
Cls[,
...])
Called to create a new instance of classCls.new()
Is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. the remaining arguments are those passed to the object constructor expression (the call to the class ). the return valuenew()
Shocould be the new object instance (usually an instanceCls).
Typical implementations create a new instance of the class by invoking the superclass'snew()
Method usingsuper(currentclass, cls).new(cls[, ...])
With appropriate arguments and then modifying the newly-created instance as necessary before returning it.
Ifnew()
Returns an instanceCls, Then the new instance'sinit()
Method will be invoked likeinit(self[, ...])
, WhereSelfIs the new instance and the remaining arguments are the same as were passednew()
.
Ifnew()
Does not return an instanceCls, Then the new instance'sinit()
Method will not be invoked.
new()
Is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.
Call an instance to generate a new class,Cls.New () is a static method (which does not need to be declared). the class itself (cls) is the first parameter, other parameters are the expressions passed to the object constructor (calls to classes). The return value of new () should be a new object instance (usually a cls instance ). A typical implementation method is to call the new () method (super (currentclass, cls) of the parent class before returning the newly generated instance ). new (cls [,...]) to change the instance object. for example, you can remove the spaces in the instance (I added this sentence myself ).
If new () returns a cls instance object, the init () method (init [,...]) of the new instance will be called. self indicates that the remaining parameters of the newly created instance are the same as those passed to new.
If new () fails to return a cls instance, the init () method of the instance will not be called.
New () is mainly used to create a subclass custom instance of an unchangeable type (such as int, str, or tuples. You can also override the custom meta class to create a custom class.
For example, before instantiating an object, you can use new to process the string. the following example is a space removal process.
class Word(str): def __new__(cls,word): if ' ' in word: print("there is qutos") word = ''.join(word.split()) return str.__new__(cls,word) a = Word('hello sherry')print(a)
The above is a detailed description of the new method of python. For more information, see other related articles in the first PHP community!