2011-05-28 27 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)