Summary of the Differences of _new_ in Different python Versions

  • 2021-08-17 00:38:21
  • OfStack

We all know that different versions of python are different when they are used. Since we recommend our friends to choose python3 version, we don't know much about the differences in this respect. Take _new_ for example, the writing in python2 and 3 is different, and the friends who came into contact with _new_ before must not have noticed this problem. Let's talk about the basic usage of new, and then give a detailed explanation of the differences between _new_ in different versions of python.

The new method takes the same parameters as init1, but init is called after the class instance is created, and the new method is the method that creates this class instance.


class Person(object):
  """Silly Person"""
  def __new__(cls, name, age):
    print '__new__ called.'
    return super(Person, cls).__new__(cls, name, age)
  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__':
  piglei = Person('piglei', 24)
print piglei

__new__ is used differently in Python3 and Python2

Writing of Python3


class Singleton(object):
  def __new__(cls,*args, **kwargs):
    if not hasattr(cls,'_inst'):
      print(cls)
      cls._inst = super(Singleton, cls).__new__(cls)
    return cls._inst

If Python3 is written in the same way as Python2, an error will be reported in the penultimate line


"TypeError: object() takes no parameters"

According to the above running results, we can find that it is not feasible to use the writing method of python2 forcibly in python3.

Python __new__ () Knowledge Point Extension

__new__ () is a static method responsible for creating an instance of a class that does not need to be decorated with an staticmethod decorator and is invoked prior to the __init__ () initialization method.

1 In general, an implementation that overrides __new__ () will call super (). __new__ () of its superclass with appropriate parameters and modify the instance before returning. For example:


class demoClass:
  instances_created = 0
  def __new__(cls,*args,**kwargs):
    print("__new__():",cls,args,kwargs)
    instance = super().__new__(cls)
    instance.number = cls.instances_created
    cls.instances_created += 1
    return instance
  def __init__(self,attribute):
    print("__init__():",self,attribute)
    self.attribute = attribute
test1 = demoClass("abc")
test2 = demoClass("xyz")
print(test1.number,test1.instances_created)
print(test2.number,test2.instances_created)

The output is

__new__(): < class '__main__.demoClass' > ('abc',) {}
__init__(): < __main__.demoClass object at 0x0000026FC0DF8080 > abc
__new__(): < class '__main__.demoClass' > ('xyz',) {}
__init__(): < __main__.demoClass object at 0x0000026FC0DED358 > xyz
0 2
1 2


Related articles: