Tuesday 15 July 2014

python - Using base class member to keep track of derived class instances -


I want to keep track of the examples of all classes that come from the base class, and if I do the following Is common, or if it presents serious damage, is it pattern or antipaten?

  class animal (object): all_animals = [] def __init __ (self): self.all_animals.append (self) class dog (animal): def __init __ (self): # The stuff here ... super (dog, self) .__ init __ () class person (animal): def __init __ (self): # other stuff here ... super (person, self) .__ init (__)  

Is this a recommended way of working? Is there a problem in this method when a large project or multiple files are inherited? For example, can I rely on a consistent Animal.all_animals cache?

One point in your view is that the list will prevent collecting garbage after a list is not found. The reference left them. For example, if the examples are disturbed and in some cases the order does not matter, then we can use the examples to store and store the examples in the __init __ method Instead we can use a metaclass whenever an example is built. (If you want a list you can use the package from PyPI)

When we instantiate a class, then its meta code's __ call __ method first It is said that we can store the example in addition to weak except it is more understandable if we only all_animals are only Animal class Allow me to access, so I used it whose __ get __ method only gives us animal by the class. WeakSet class meta (type): def __call __ (self) from weak import: example = super (meta, self) .__ call __ () Animal.all_animals.add (example) Back to

 Example class Animal_prop: def __init __ (self, cls = WeakSet): self.all_animals = cls () def __get __ (self, ins, cls): If IS is none and CL is animal: return self . All _animals Other: Enhance Enterprise Class Animal (Object): __metaclass__ = Meta all_animals = Animals_prop () def __del __ (self): The example of print "{} is dead." Format (type (self) .__ name__) class dog (animal): pass class person (animal): if __name__ == '__main__': a = animal () b = dog () c = person () print set ( Animal.all_animals) Dell C print set (Animal.all_animals) Print '-' * 10  

Output:

  set ([. & Lt; __ Main __ Animal 0x1012f5590 & gt;; Object on; __ main__.Dog object 0x1012f55d0 & gt ;, & lt; __ 0x1012f5610 & gt; main __ person object ;.]) Example of person He is dead. Set (animal.] On the item (__ main___ 0x1012f5590 & gt;, & lt;) at the rate of 0x1012f55d0; ---------- The animal instances are dead. The example of a dog is dead  

No comments:

Post a Comment