python-3.x - Python根据属性获取类对象名称
问题描述
例如,我如何获得座位 3 的玩家姓名?谢谢!
请注意,我不知道 p3 中的一个。
class Player:
def __init__(self, name, seat, balance):
self.name = name
self.seat = seat
self.balance = balance
dealer = Player('Dealer', 7, 1000)
p1 = Player('Player1', 1, 100)
p2 = Player('Player2', 2, 100)
p3 = Player('Player3', 3, 100)
p4 = Player('Player4', 4, 100)
p5 = Player('Player5', 5, 100)
p6 = Player('Player6', 6, 100)
解决方案
我想您并不是只想打印名称p3.name
。
如果您要跟踪类的所有实例,请参阅:Python:按值查找类的实例和如何跟踪类实例?
如果我应用与上面引用的两个参考文献中提到的相同的逻辑,您的代码可能如下所示:
class Player(object):
# create a class attribute to keep track of all the instances of the class
instances = []
def __init__(self, name, seat, balance):
self.name = name
self.seat = seat
self.balance = balance
Player.instances.append(self)
# class method to access player instances by seat
@classmethod
def get_players_at_seat(cls, seat):
return (p for p in cls.instances if p.seat == seat)
dealer = Player('Dealer', 7, 1000)
p1 = Player('Player1', 1, 100)
p2 = Player('Player2', 2, 100)
p3 = Player('Player3', 3, 100)
p4 = Player('Player4', 4, 100)
p5 = Player('Player5', 5, 100)
p6 = Player('Player6', 6, 100)
# Get iterator containing all players at seat 3
players_at_seat_3 = Player.get_players_at_seat(3)
# Print their names
for player in players_at_seat_3:
print(f"{player.name} is sitting at seat 3")
该get_players_at_seat()
函数是一个类方法,它返回一个迭代器,其中包含所有instances
属性seat
设置为给定值的玩家seat
。然后,您可以遍历迭代器并打印座位 3 的玩家姓名。
推荐阅读
- intellij-idea - 换行时的 Intellij IDEA 逗号位置
- javascript - 无法通过 xpath 找到元素(JS 激活网站 Selenium chrome)
- python - 根据日期列和日期范围填充 Pandas 数据框
- azure - 尽管调用 SetMetadataAsync() 然后 UploadBlobAsync() 在 blob 中找不到元数据或标签
- django - django 模型根据与用户 FK 配置文件相关的布尔字段 True/False 对查询集进行排序
- python - 是否可以在不使用子图的情况下拥有辅助 Y 轴
- django - 如何在django中显示复选框多选
- python - Tensorflow:SSD_mobilenet_v2_2 中的 TFLiteConverter(保存模型 -> TFLite)
- for-loop - 批处理:如何在嵌套的 for 循环中设置变量并在其外部重新使用它(enabledelayedexpansion 不起作用)
- r - 我们可以在 R 森林图中用不同颜色为不同的行/协变量/研究着色吗?