Article From:

Through the decorator or __new__, you can implement singletons or caching instances.
Can it limit the number of instances created by the class and create a certain number before it can be created? Because there is a cost to create instances.

Answer 0:
  1. If you must limit the number, create a class variable count.override __new__ Realization of control
  2. If it is only to solve the memory overhead, it can be passed.__slots__Attribute restriction, not quantity restriction.
Answer 1:

Record the number of instances that have been generated in the class, then determine in u new_u whether the number has reached the limit, and if so, do not return the instance. Of course, remember to reduce the quantity in __delete__.

But new should be your control.

Leave a Reply

Your email address will not be published. Required fields are marked *