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:
- [design and development] Python learning notes – Super () argument 1 must be type, not classobj
- Python TypeError: not all arguments converted during string formatting
- Python Typeerror: super() takes at least 1 argument (0 given) error in Python
- [Solved] IllegalArgumentException: object is not an instance of declaring class
- Python Error-TypeError:takes 2 positional arguments but 3 were given
- AttributeError: ‘tuple’ object has no attribute ‘extend’
- How to Solve Python TypeError: ‘module’ object is not callable
- Fast locating nonetype ‘object is not Iterable in Python
- Python3 urlopen() TypeError: can’t convert ‘bytes’ object to str im…
- Python Standard Library: functools (cmp_to_key, lru_cache, total_ordering, partial, partialmethod, reduce, sing…