Tracking Class Instances for Variable Collection
Maintaining a list of instances for a particular class allows for efficient retrieval of specific variables from each instance at a later program stage.
Class Variable Approach
A suitable method for tracking class instances is to utilize a class variable. The following example illustrates this approach:
class Foo: instances = [] def __init__(self): self.x = {} Foo.instances.append(self)
This technique creates a shared list instances within the class. As each instance is created, it appends itself to the list.
Retrieving Instance Variables
To collect x dictionaries from all instances at the end of the program, create a new dictionary:
foo_vars = {id(instance): instance.x for instance in Foo.instances}
Here, id() provides unique identifiers for each instance, enabling the creation of a dictionary with instance IDs as keys and x dictionaries as values.
Shared List
The class variable approach ensures that only one list, instances, is maintained across all instances, regardless of their number. This eliminates the need to track individual lists for each instance.
The above is the detailed content of How to Efficiently Track and Retrieve Instance Variables in Python Classes?. For more information, please follow other related articles on the PHP Chinese website!