1, init and new methods
__The main differences between init and new are:
1. Init is usually used to initialize a new instance and control the initialization process, such as adding some properties and doing some extra operations, which occurs after the class instance is created. It is an instance level method.
2. New is usually used to control the process of generating a new instance. It's a class level method.
class Animal(object): def __new__(cls, *args, **kwargs): print("instance create.") return object.__new__(cls) # Returns an instance object. self refers to it def __init__(self, name): print("instance init.") self.name = name animal = Animal('W')
instance create. instance init.
# -*- coding: utf-8 -*- class Person(object): def __new__(cls, name, age): print('__new__ called.') return super(Person, cls).__new__(cls) 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) if __name__ == '__main__': p = Person('wang', 24) print(p)
__new__ called. __init__ called. <Person: wang(24)>
2, The role of new
According to the official Python documentation, the "new" method mainly provides you with a way to customize the instantiation process of these classes when you inherit some immutable classes (such as int, str, tuple). There is also the implementation of custom metaclass.
Example 1: create an integer type that is always positive:
class PositiveInteger(int): def __new__(cls, value): return super(PositiveInteger, cls).__new__(cls, abs(value)) i = PositiveInteger(-6) print(i)
3, To implement a singleton
class Singleton(object): def __new__(cls): # The key is that every time we instantiate, we will only return the same instance object if not hasattr(cls, 'instance'): cls.instance = super(Singleton, cls).__new__(cls) return cls.instance obj1 = Singleton() obj2 = Singleton() obj1.attr1 = 'value1' print(obj1.attr1, obj2.attr1) print(obj1 is obj2)
value1 value1 True