python __new__

new
实验
实验1
实验2
应用:实现单例

new

This method is only used for new-style classes (classes inheriting from object).

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.

  • 静态方法
  • 构建cls对象
  • 如果__new__返回cls实例,__init__将被调用
  • 如果__new__返回为空,__init__不会被调用
  • init 实例方法,初始化实例

实验

实验1

  • 重写new 但是不返回实例
  • code
  1. class A(object):
  2. a = 1
  3. def __new__(cls, *args, **kwargs):
  4. print ‘+ A new‘
  5. inst = super(A, cls).__new__(cls, *args, **kwargs)
  6. print ‘- A new‘
  7. #return inst
  8. def __init__(self):
  9. print ‘+ A init‘
  10. print ‘- A init‘
  11. a = A()
  12. print type(a)
  13. + A new
  14. - A new
  15. <type ‘NoneType‘>
  • 结论:

    1 new无cls实例返回,初始化实例后将位None

    2 init方法并没有被调用

实验2

  • new 方法重写,调用超类的new并返回实例
  1. class A(object):
  2. a = 1
  3. def __new__(cls, *args, **kwargs):
  4. print ‘+ A new‘
  5. inst = super(A, cls).__new__(cls, *args, **kwargs)
  6. print ‘- A new‘
  7. return inst
  8. def __init__(self):
  9. print ‘+ A init‘
  10. print ‘- A init‘
  11. a = A()
  12. print type(a)
  13. 结果
  14. + A new
  15. - A new
  16. + A init
  17. - A init
  18. <class ‘__main__.A‘>

应用:实现单例

  1. class A(object):
  2. _inst = None
  3. def __new__(cls, *args, **kwargs):
  4. print ‘+ A new‘
  5. if not cls._inst:
  6. print ‘do new.‘
  7. cls._inst = super(A, cls).__new__(cls, *args, **kwargs)
  8. cls._inst.inst_count = 0
  9. print ‘- A new‘
  10. return cls._inst
  11. def __init__(self):
  12. print ‘+ A init‘
  13. self.inst_count += 1
  14. print ‘- A init‘
  15. a = A()
  16. print type(a), a.inst_count
  17. aa = A()
  18. print type(aa), aa.inst_count
  19. aaa = A()
  20. print type(aaa), aaa.inst_count
  • 结果
  1. + A new
  2. do new.
  3. - A new
  4. + A init
  5. - A init
  6. <class ‘__main__.A‘> 1
  7. + A new
  8. - A new
  9. + A init
  10. - A init
  11. <class ‘__main__.A‘> 2
  12. + A new
  13. - A new
  14. + A init
  15. - A init
  16. <class ‘__main__.A‘> 3

来自为知笔记(Wiz)

时间: 2024-11-05 00:38:42

python __new__的相关文章

python __new__以及__init__

@[深入Python]__new__和__init__ 1 2 3 4 5 6 7 8 class A(object):     def __init__(self):         print "init"     def __new__(cls,*args, **kwargs):         print "new %s"%cls         return object.__new__(cls, *args, **kwargs) A() 输出: new

Python: __new__ magic method explained

https://howto.lintel.in/python-__new__-magic-method-explained/ Python: __new__ magic method explained Python is Object oriented language, every thing is an object in python. Python is having special type of  methods called magic methods named with pr

飘逸的python - __new__、__init__、__call__傻傻分不清

__new__: 对象的创建,是一个静态方法.第一个參数是cls.(想想也是,不可能是self,对象还没创建,哪来的self) __init__ : 对象的初始化, 是一个实例方法,第一个參数是self. __call__ : 对象可call.注意不是类,是对象. 先有创建,才有初始化.即先__new__,而后__init__. 上面说的不好理解,看样例. 对于__new__ class Bar(object): pass class Foo(object): def __new__(cls,

python __new__()和__init__()哪个更早?

通过代码验证是最靠谱的: class Foo(object): def __init__(self): print 'foo init' def __new__(cls,*args,**kwargs): print 'foo new' return object.__new__(cls,*args,**kwargs) foo = Foo() print type(foo) 结果: >>> foo new foo init <class '__main__.Foo'> >

python __new__中单例的作用

#单例的作用就是为了节约系统资源,每每生成一个对象的时候都回去占用内存空间,因此单例就可以结局这个问题 #非单例模式,非单例模式在每次实例化的时候都会去调用内存生,这样调用的次数多了,就可能会造成内存的浪费 class A(object):     pass a=A() b=A() print(id(a)) print(id(b)) 输出结果 3000151570976 3000151571312 #单例模式 #讲解:在类开始之前会调用类的new方法去生成一个对象,所以我们只需要在类调用钱做处理

python __new__, __init__,__call__区别

转载link:http://pycoders-weekly-chinese.readthedocs.io/en/latest/issue6/a-guide-to-pythons-magic-methods.htmlc

设计模式之单例模式与工厂模式的Python实现(一)

1. 单例模式 单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在.当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场. 比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息.如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会

Python中的__new__()方法的使用

__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 s

Python构造器及析构器:__init__与__new__及__del__

__init__与__new__这两个魔法方法组成了Python类对象的构造器,在Python类实例化时,其实最先调用的不是__init__而是__new__.__new__是负责实例化对象的,而__init__是初始化操作.__del__是析构器,当Python对象的所有引用都不存在了(被del了),就会自动触发__del__执行. class CapStr(str): def __new__(cls, string): #此时string = 'i love you' cls是CapStr这