Python: __ new__ Method and the processing of typeerror: object() takes no parameters

Some Python books or blogs use the__ init__ Methods are called constructors, which is not strict because the method that creates the instance is__ new__, The method of instance initialization is__ init__, __ new__ Method returns an instance, and__ init__ Return to none

In understanding__ init__ And__ new__ I found an article: explain the differences in Python__ init__ And__ new__, There is this Code:

# -*- coding: utf-8 -*-
class Person(object):
    """Silly Person"""
 
    def __new__(cls, name, age):
        print ('__new__ called.')
        return super().__new__(cls, name, age)  # >>>>wrong<<<<
 
    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)

Error: typeerror: object() takes no parameters

Obviously, the base class object does not accept parameters, so you need to change the line in question to:

return super().__ new__( cls)

In fact, the above example is unnecessary__ new__ Method, just to show the order of method calls__ new__ Method is used when inheriting some immutable classes (such as int, STR, tuple). For example, to create a float type that always retains two decimal places, you can write as follows:

# -*- coding: utf-8 -*-
class RoundFloat(float):
    def __new__(cls, value):
        return super().__new__(cls, round(value, 2))   
 
print(RoundFloat(3.14159))  #3.14

Similar Posts: