gpt4 book ai didi

Python 多类

转载 作者:行者123 更新时间:2023-11-28 19:59:04 25 4
gpt4 key购买 nike

我想创建多个具有自己唯一 ID 的机器人。但是如何为众多机器人自动执行此操作并拥有所有其他 ID?我可以使用 bot1、bot2,但如果我想将它与 100 个机器人一起使用怎么办?

class newbot:
id = randomid()


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

最佳答案

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

关于Python 多类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6160705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com