笔记-python-__new__()

笔记-python-__new__()

 

1.       __new__()

__new__() 是在新式类中新出现的方法,它作用在构造方法建造实例之前.

验证代码:

class Person(object):

    def __new__(cls, name, age):

        print('__new__ called.')

        instance = super(Person, cls).__new__(cls)

        return instance

 

    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)

 

name = Person('xxx', 45)

print(name)

输出:

__new__ called.

__init__ called.

<Person:xxx(45)

 

可以发现new是在init之前调用的,对于整个实例化过程可以这样理解:

  1. name = Person(‘xxx’,45)
  2. 首先执行new方法,返回一个Personal类的一个实例;
  3. 利用实例调用init方法,初始化实例。

 

 

1.1.    __new__()使用

一般情况下不需要做如此细颗粒度的操作,但在一些需要操纵类实例化细节的时候,就需要使用__new__了。

典型的场景时单例模式实现:

 

# singleton __new__()

class Singleton(object):

    _instance = None

 

    def __new__(cls, *args, **kwargs):

        if not cls._instance:

            cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)

        return cls._instance

 

class Myclass(Singleton):

    a = 1

 

a1 = Myclass()

a2 = Myclass()

print(a1 == a2, a1 is a2)

重载new,在类实例化时通过new进行判断,返回已有类或生成新类。

 

1.2.    附加内容

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 subtype of T """

    pass

 

1.3.    问题

 

class Person(object):

    def __new__(cls, name, age):

        print('__new__ called.')

        instance = super(Person, cls).__new__(cls,name,age)

        return instance

 

    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)

 

name = Person('xxx', 45)

print(name)

使用后报错:TypeError: object() takes no parameters

 

posted @ 2018-10-16 17:51  木林森__𣛧  阅读(133)  评论(0)    收藏  举报