2011-05-28 63 views
2

我想用自己的唯一ID創建多個機器人。但是,如何自動爲大量機器人做這件事,並擁有所有其他ID?我可以使用bot1,bot2但是如果我想用100個機器人使用它呢?Python多個類

class newbot: 
    id = randomid() 


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

回答

7

id成員結束了你的類的所有實例之間共享,因爲它定義爲類成員,而不是實例成員。你或許應該寫:

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 
3

使用內置函數ID()這一點。構造新的空對象並獲取id(obj)。

或者你可以得到ID(bot1),身份證(bot2)

嘗試了下:

def getRandId(self): 
    return id(self)