python __new__方法
来源:互联网 发布:python 字典添加 编辑:程序博客网 时间:2024/06/18 12:14
通常我们把 __init__ 称为构造方法,这是从其他语言借鉴过来的术语。
用于构建实例的是特殊方法 __new__:这是个类方法,必须返回一个实例,返回的实例会作为第一个参数(即self)传给 __init__ 方法。
调用 __init__ 方法时要传入实例,且禁止返回所以 __init__ 方法其实是初始化方法。
真正的构造方法是 __new__,不需要自己编写 __new__ 方法,从 object 类继承的实现已经足够了。
__new__ 是类方法,第一个参数是类本身,余下的参数与 __init__ 方法一样,只不过没有self。
class A: def __new__(cls, arg): print(arg) print(cls) return super().__new__(cls) def __init__(self, num): print("__init__ : {}".format(num)) >>> a = A(1)1<class '__main__.A'>__init__ : 1
从 __new__ 方法到 __init__ 方法,是最常见的,但不是唯一的。 __new__ 方法也可以返回其他类的实例,此时,解释器不会调用 __init__ 方法。
class A: passclass B: def __new__(cls, arg): print(arg) print(cls) return A() def __init__(self, num): print("__init__ : {}".format(num))>>> b=B(1)1<class '__main__.B'>
阅读全文
2 0
- python中的__new__()方法
- Python的__new__方法
- python中的__new__方法
- python __new__方法
- 关于python中的__new__方法
- 详解python中的__new__方法
- python metaclass 和 __new__方法
- Python __new__() 方法与__init__()方法
- Python 之 __new__() 方法与实例化
- Python 之 __new__() 方法与实例化
- Python---类的"__new__"和"__init__"方法
- Python 之 __new__() 方法与实例化
- python魔法方法——(__new__)
- Python中__new__方法的使用
- Python中的__new__()方法的使用实例
- Python 之 __new__() 方法与实例化
- Python 之 __new__() 方法与实例化
- Python class的__new__与__init__方法
- 高数 01.08函数的连续性与间断点
- PCB元件布局原则与实用小技巧
- 集成 Jenkins 和 TestNG 实现自助式自动化测试平台
- 第五章 栈和队列
- MVP模式在Android开发中的应用
- python __new__方法
- SVN检测的项目报错---解决办法
- ofo产品体验&共享单车精细化运营的思考
- win10下通过wubi.exe安装ubuntu
- 关于UILongPressGestureRecognizer调用多次的问题
- 程序运行时间
- 虚函数(C++)
- 用9path图片做背景 button和textview的文字不显示
- Windows下用QtCreator和C++写Android程序-上