Feb-23-2019, 02:34 AM
(This post was last modified: Feb-23-2019, 02:41 AM by AlekseyPython.)
Class variables contain variables common to all objects of the class and thus show the inalienable properties of the objects. But unfortunately, they are not collected by the garbage collector, because they belong to the whole class, which in turn belongs to a module, which are very rarely unloaded. Therefore, I see three strategies for their use:
1. In class variables, store the necessary user objects, and for all objects that need to call the destructor explicitly
2. Class variables store auxiliary data that, on the one hand, allows you to see common features of the class, and on the other hand, they are easily converted to real objects during initialization in the init() method
3. Discard class variables because no garbage collector is called for them.
What is the best strategy to use?
1. In class variables, store the necessary user objects, and for all objects that need to call the destructor explicitly
1 2 3 4 |
class MyClass: WRITER = writers.DbWriter() def __del__( self ): self .WRITER.close() |
1 2 3 4 5 |
class MyClass: WRITER = 'DbWriter' def __init__( self ): if WRITER = = 'DbWriter' : self .writer = writers.DbWriter() |
1 2 3 |
class MyClass: def __init__( self ): self .writer = writers.DbWriter() |