开发小游戏遇问题:如何判断成员Email是否已分配至Player实例?
判断Player实例的邮箱是否已存在
你的现有代码没法实现需求,直接判断字符串在file2模块里是无效的——file2只是定义了几个Player变量,Python没法直接从模块中检索实例的属性值。下面是两种可行的解决方式:
方案1:用列表统一管理Player实例
先修改file2,把所有Player实例存入一个列表:
# file2.py player1 = Player("testName1", "test1@gmail.com", "testpwd1") player2 = Player("testName2", "test2@gmail.com", "testpwd2") player3 = Player("testName3", "test3@gmail.com", "testpwd3") player4 = Player("testName4", "test4@gmail.com", "testpwd4") # 将所有玩家实例汇总到列表中 all_players = [player1, player2, player3, player4]
然后在file1中遍历列表,检查每个实例的邮箱属性:
# file1.py from file2 import all_players target_email = "test1@gmail.com" # 用any()快速判断是否存在匹配的邮箱 email_exists = any(player.email == target_email for player in all_players) if email_exists: print("ok") else: print("not ok")
注意:需要确保你的Player类正确初始化了email属性,类定义示例:
class Player: def __init__(self, name, email, password): self.name = name self.email = email self.password = password
方案2:用字典存储(更高效的查找)
如果玩家数量较多,用字典以邮箱为键存储实例,能实现O(1)时间复杂度的查找:
# file2.py player1 = Player("testName1", "test1@gmail.com", "testpwd1") player2 = Player("testName2", "test2@gmail.com", "testpwd2") player3 = Player("testName3", "test3@gmail.com", "testpwd3") player4 = Player("testName4", "test4@gmail.com", "testpwd4") # 以邮箱为键,玩家实例为值构建字典 players_by_email = { player1.email: player1, player2.email: player2, player3.email: player3, player4.email: player4 }
在file1中直接检查字典的键是否存在:
# file1.py from file2 import players_by_email target_email = "test1@gmail.com" if target_email in players_by_email: print("ok") else: print("not ok")
内容的提问来源于stack exchange,提问作者ENDERastronaute
相关产品推荐
相关产品推荐

