首页 > 解决方案 > 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)

标签: python-3.xclass

解决方案


我想您并不是只想打印名称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 的玩家姓名。


推荐阅读