博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 特殊方法之new
阅读量:4453 次
发布时间:2019-06-07

本文共 1942 字,大约阅读时间需要 6 分钟。

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

Called to create a new instance of class cls. 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 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 method using super(currentclass, cls).__new__(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it.

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

If does not return an instance of cls, then the new instance’s method will not be invoked.

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

如果__new()__返回了一个cls的实例对象,然后就会调用这个新的实例的__init()__方法(__init__[,...]),self指新创建的实例其余的参数和传递给__new()的一样。

如果__new()__没有成功返回一个cls的实例,就不会调用这个实例的init()方法。

__new()__主要用来进行不可变类型(像是int,str,或者元组)的子类自定义实例的创建。也可以重写自定义元类来进行自定义类的创建。

举例:在实例化对象之前,先将字符串做一个处理,就可以用__new__,下面的例子就是做一个去空格处理。

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)
View Code

 

转载于:https://www.cnblogs.com/guoxueyuan/p/6497896.html

你可能感兴趣的文章
DataTable导出为word,excel,html,csv,pdf,.txt
查看>>
android ListView详解
查看>>
软件工程 第一次作业
查看>>
Content Server HA搭建
查看>>
vue-textarea 自适应高度
查看>>
(2)数据结构——线性表(链表)实现
查看>>
[leetCode]Linked List Cycle I+II
查看>>
leetcode中的python学习
查看>>
sqlserver打开对象资源管理器管理的帮助文档的快捷键
查看>>
JBOSSAS 5.x/6.x 反序列化命令执行漏洞(CVE-2017-12149)
查看>>
Zookeeper zkui-zookeeper图形化管理工具
查看>>
java运行时内存分类
查看>>
为什么说 Git 比 SVN 更好
查看>>
1.基础数据类型的初识 字符串 bool 整型 if else elif
查看>>
【设计模式】4、原型模式
查看>>
进入meta模式关闭背光灯
查看>>
webstorm上svn的安装使用
查看>>
【JEECG技术文档】数据权限自定义SQL表达式用法说明
查看>>
使用 Bootstrap Typeahead 组件
查看>>
EF不能很好的支持DDD?估计是我们搞错了!
查看>>