__init__和__new__

1 __init__和__new__的区别

  1 当创建一个实例的时候会首先调用__new__, 然后在初始化实例的时候会调用__init__.

  2 __new__是类级别的方法,__init__是个实例方法.

  3 __new__方法会返回一个创建的实例,而__init__不需要有返回值

2 __new__ 实际应用

2.1 在元类中的应用

# 由type创建元类,必须要继承type
class MetaClassFoo(type):

    # 由元类创建类也遵循 名字;继承;方法
    def __new__(cls, name, base, attrs):
        # 天赋,赋予给通过该元类创建的类
        attrs['func'] = lambda self: 'im %s and i have func!' % self.name
        return type.__new__(cls, name, base, attrs)


# 由元类创建类
class Foo(object):

    __metaclass__ = MetaClassFoo

    def __init__(self):
        self.name = 'www'


# 由类创建实例,并生成方法
print Foo().func()

2.2 在单例模型中的应用

class Singleton(object):
    _instance = None  # 定义一个类属性,而这个类属性绑定的是这个类第一次创建的对象

    def __init__(self, name):
        self.name = name

    def __new__(cls, *args, **kwargs):
        if not cls._instance:  # 如果没有类属性就新建一个
            cls._instance = super(Singleton, cls).__new__(cls, *args)
        return cls._instance  # 返回这个类属性,并且这个类属性是这个类的第一次创建对象


a = Singleton('www')
a2 = Singleton('wdd')

print a.name  # wdd
print a2.name  # wdd
print a is a2  # True
print a == a2  # True
print a  # <__main__.Singleton object at 0x000000000254D8D0>
print a2  # <__main__.Singleton object at 0x000000000254D8D0>

__new__方法是创建对象,返回时类属性,所以和实例属性相不相等没有关系,因为类属性是一样的。

原文地址:https://www.cnblogs.com/fuzzier/p/7811765.html