Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python multiple classes

Tags:

python

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
like image 545
user774166 Avatar asked Jul 26 '26 06:07

user774166


2 Answers

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  
like image 169
Frédéric Hamidi Avatar answered Jul 28 '26 21:07

Frédéric Hamidi


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 )
like image 26
sergzach Avatar answered Jul 28 '26 21:07

sergzach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!