笔记-python-__new__()

1.       __new__()

__new__() 是在新式类中新出现的方法,它作用在构造方法建造实例之前.

验证代码:

class Person(object):

def __new__(cls, name, age):

print('__new__ called.')

instance = super(Person, cls).__new__(cls)

return instance

def __init__(self, name,age):

print('__init__ called.')

self.name = name

self.age = age

def __str__(self):

return '<Person:%s(%s)' %(self.name, self.age)

name = Person('xxx', 45)

print(name)

输出:

__new__ called.

__init__ called.

<Person:xxx(45)

可以发现new是在init之前调用的,对于整个实例化过程可以这样理解:

  1. name = Person(‘xxx’,45)
  2. 首先执行new方法,返回一个Personal类的一个实例;
  3. 利用实例调用init方法,初始化实例。

1.1.    __new__()使用

一般情况下不需要做如此细颗粒度的操作,但在一些需要操纵类实例化细节的时候,就需要使用__new__了。

典型的场景时单例模式实现:

# singleton __new__()

class Singleton(object):

_instance = None

def __new__(cls, *args, **kwargs):

if not cls._instance:

cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)

return cls._instance

class Myclass(Singleton):

a = 1

a1 = Myclass()

a2 = Myclass()

print(a1 == a2, a1 is a2)

重载new,在类实例化时通过new进行判断,返回已有类或生成新类。

1.2.    附加内容

new只能用于从object继承的新式类。

object中对new方法的定义如下:

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

1.3.    问题

class Person(object):

def __new__(cls, name, age):

print('__new__ called.')

instance = super(Person, cls).__new__(cls,name,age)

return instance

def __init__(self, name,age):

print('__init__ called.')

self.name = name

self.age = age

def __str__(self):

return '<Person:%s(%s)' %(self.name, self.age)

name = Person('xxx', 45)

print(name)

使用后报错:TypeError: object() takes no parameters

笔记-python-__new__()的更多相关文章

  1. MongoDB学习笔记:Python 操作MongoDB

    MongoDB学习笔记:Python 操作MongoDB   Pymongo 安装 安装pymongopip install pymongoPyMongo是驱动程序,使python程序能够使用Mong ...

  2. python __new__以及__init__

    @[深入Python]__new__和__init__ 1 2 3 4 5 6 7 8 class A(object):     def __init__(self):         print & ...

  3. 笔记-python操作mysql

    笔记-python操作mysql 1.      开始 1.1.    环境准备-mysql create database db_python; use db_python; create tabl ...

  4. 笔记-python异常信息输出

    笔记-python异常信息输出 1.      异常信息输出 python异常捕获使用try-except-else-finally语句: 在except 语句中可以使用except as e,然后通 ...

  5. 笔记-python -asynio

    笔记-python -asynio 1.      简介 asyncio是做什么的? asyncio is a library to write concurrent code using the a ...

  6. 笔记-python lib-pymongo

    笔记-python lib-pymongo 1.      开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...

  7. 笔记-python tutorial-9.classes

    笔记-python tutorial-9.classes 1.      Classes 1.1.    scopes and namespaces namespace: A namespace is ...

  8. 机器学习实战笔记(Python实现)-08-线性回归

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

  9. 机器学习实战笔记(Python实现)-05-支持向量机(SVM)

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

  10. 机器学习实战笔记(Python实现)-04-Logistic回归

    --------------------------------------------------------------------------------------- 本系列文章为<机器 ...

随机推荐

  1. c# string.format 的简写 $

    var name = "huchao"; var info = $"你是谁,我叫:{name}"; Console.Write(info); Console.R ...

  2. 使用AOP监控用户操作并插入数据库

    引入依赖 <!--spring切面aop依赖--> <dependency> <groupId>org.springframework.boot</group ...

  3. JavaSE之Java基础(4)

    16.String.StringBuilder和StringBuffer的区别 String类是final的,不可变,StringBuilder和StringBuffer可变: 大部分情况下的执行效率 ...

  4. mysql-作业

    一.表关系 请创建如下表,并创建相关约束                 班级表:class       学生表:student       cid caption grade_id   sid sn ...

  5. cron 任务执行表达式

    1.来源 开始我还不知道cron到底来源于哪里,不求甚解的我也没做过多了解,现在突然用到所以写一下. cron计划任务  其实只是linux 一个执行计划的一个工具或者执行程序. 在Linux系统中, ...

  6. 私有npm下载资源

    私有npm库下载资源需要用户名和密码,这个需要创建npm库的人提供. 使用方法: npm login --registry=仓库地址 Username: 用户名 Password: 密码 Email: ...

  7. 优化Linux的内核参数来提高服务器并发处理能力

    提高Linux系统下的负载能力,可以使用nginx等原生并发处理能力就很强的web服务器 使用Apache的可以启用其Worker模式,来提高其并发处理能力 修改Linux的内核相关TCP参数,来最大 ...

  8. 如何查看与显示oracle表的分区信息

    显示分区表信息 显示数据库所有分区表的信息:DBA_PART_TABLES 显示当前用户可访问的所有分区表信息:ALL_PART_TABLES 显示当前用户所有分区表的信息:USER_PART_TAB ...

  9. RStudio Server-0.99.902 (OpenLogic CentOS 7.2)

    RStudio Server-0.99.902 (OpenLogic CentOS 7.2) 0 评论 平台: CentOS 类型: 虚拟机镜像 软件包: r-3.2.3 rstudio-server ...

  10. Python变量状态保持四种方法

    Python状态保持 ​ 全局 global def tester(start): global state state = start def nested(label): global state ...