object. new (cls[, ...])

Called to create a new instance of class cls. 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 value of new() should be the new object instance (usually an instance of cls).

Typical implementations create a new instance of the class by invoking the superclass’s new() method using super(currentclass, cls).new(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it.

If new() returns an instance of cls, then the new instance’s init() method will be invoked like init(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to new().

If new() does not return an instance of cls, then the new instance’s init() 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.

调用产生一个新的类的实例,cls. new()是一个静态方法(不需要声明),类本身(cls)作为第一个参数,其他的的参数是传递给对象构造函数的表达式(对类的调用),new()的返回值应该是一个新的对象实例(一般是cls的实例)。典型的实现方法就是在返回新生成的实例之前,调用父类的new()方法(super(currentclass, cls).new(cls[, ...]))来改变这个实例对象,比如说可以把实例里面字符的空格去掉等等(这句是我自己加的)。





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')

以上就是关于python 特殊方法之new的详细内容,更多请关注ki4网其它相关文章!