user774166
user774166

Reputation: 45

Python multiple classes

I want to create multiple bots with all their own unique id. But how can do this automatically for numerous bots and have all an other id? I can use bot1, bot2 but what if i want to use this with 100 bots?

class newbot:
    id = randomid()


bot1 = newbot() 
bot2 = newbot()   
print bot1.id
print bot2.id   #all the same id

Upvotes: 2

Views: 378

Answers (2)

sergzach
sergzach

Reputation: 6754

Use built-in function id() for this. Construct new empty object and get id( obj ).

Or you can get id( bot1), id( bot2 )

Try the next:

  def getRandId( self ):
    return id( self )

Upvotes: 3

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

The id member ends up being shared among all instances of your class because it's defined as a class member instead of an instance member. You probably should write:

class newbot(object):
    def __init__(self):
        self.id = randomid()

bot1 = newbot() 
bot2 = newbot()   

# The two ids should be different, depending on your implementation of randomid().
print bot1.id
print bot2.id  

Upvotes: 7

Related Questions