python 面向对象十 __init__和__new__

一、__init__和__new__方法

__init__ 和 __new__ 最主要的区别在于:
1.__init__ 通常用于初始化一个新实例,控制这个初始化的过程,比如添加一些属性, 做一些额外的操作,发生在类实例被创建完以后。它是实例级别的方法。
2.__new__ 通常用于控制生成一个新实例的过程。它是类级别的方法。

例子1:

class Animal(object):
    def __new__(cls, *args, **kwargs):
        print("instance create.")
        return object.__new__(cls)  # 返回一个实例对象,self指的就是它

    def __init__(self, name):
        print("instance init.")
        self.name = name

animal = Animal('W')
instance create.
instance init.

例子2:

# -*- 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)>

二、__new__的作用

依照Python官方文档的说法,__new__方法主要是当你继承一些不可变的class时(比如int, str, tuple), 提供给你一个自定义这些类的实例化过程的途径。还有就是实现自定义的metaclass。

例子1:创建一个永远都是正数的整数类型:

class PositiveInteger(int):
    def __new__(cls, value):
        return super(PositiveInteger, cls).__new__(cls, abs(value))
 
i = PositiveInteger(-6)
print(i)

三、__new__实现单例singleton

class Singleton(object):
    def __new__(cls):
        # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象
        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
原文地址:https://www.cnblogs.com/gundan/p/8074817.html