Kudzu
Kudzu

Reputation: 3638

Incremental instance counters in class instances

I'm writing a program which aims to generate a lot of activity in Active Directory to stress-test another piece of software. To create users, I'm creating a simple class like

class ADUser(object):
  def __init__(self):
    self.firstname = self.firstname() # returns a random name from a big list
    self.lastname = self.lastname()   # returns a random name from a big list
    self.fullname = self.firstname + " " + self.lastname
    self.employeeid = ???             # an incrementing integer... somehow

It's the employeeid attribute that's giving me trouble. I'd like to have this increment each time a user object is created -- this would guarantee a unique ID number and help me keep track of activity. However, I'm not sure how to do that within the class. I could do it outside the class easily enough with a for loop, but that doesn't seem like the cleanest or most 'Pythonic' method.

This is probably a simple question, but it's been stumping me.

Upvotes: 2

Views: 139

Answers (1)

This is the perfect usecase for a static variable.

class ADUser(object):
    numEmployees = 0
    def __init__(self):
        self.firstname = self.firstname() # returns a random name from a big list
        self.lastname = self.lastname()   # returns a random name from a big list
        self.fullname = self.firstname + " " + self.lastname
        ADUser.numEmployees += 1
        self.employeeid = ADUser.numEmployees

Upvotes: 6

Related Questions