python object-oriented 10 ﹐ init ﹐ and ﹐ new__

Keywords: Python

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.

Example 1:

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.") = name

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

Example 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.') = name
        self.age = age

    def __str__(self):
        return '<Person: %s(%s)>' % (, self.age)

if __name__ == '__main__':
    p = Person('wang', 24)
__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)

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

Posted by NNTB on Fri, 01 May 2020 01:08:13 -0700