Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting instances of a class?

Tags:

python

class

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?

like image 559
Blender Avatar asked Dec 25 '11 03:12

Blender


People also ask

How do you count instances in Python?

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.

What is an instance of a class example?

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.


1 Answers

Try something like this:

from itertools import count  class Obj(object):   _ids = count(0)    def __init__(self):     self.id = next(self._ids) 
like image 127
g.d.d.c Avatar answered Sep 28 '22 23:09

g.d.d.c