I've been cleaning up some code from a module I'm extending and I can't seem to find a way to Pythonify this code:
global_next_id = 1 class Obj: def __init__(self): global global_next_id self.id = global_next_id global_next_id += 1
This code uses a global id to keep track of instances of a class (I need the variable self.id
internally as well, and it needs to be a number).
Can anyone suggest a way to Pythonify this code?
The easiest way to count the number of occurrences in a Python list of a given item is to use the Python . count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.
Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle. Instantiation − The creation of an instance of a class. Method − A special kind of function that is defined in a class definition.
Try something like this:
from itertools import count class Obj(object): _ids = count(0) def __init__(self): self.id = next(self._ids)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With