1

How do I get a name of player in seat 3 for example? Thank you!

Note that I do not know that p3 in the one.

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)
75suited
  • 11
  • 1
  • You can put them in a list and filter items based on the `.seat` and check their `.name`s. – Asocia Apr 14 '21 at 12:59
  • With your existing code, there is no Python trick to get what you want, without extra housekeeping. You can make a map of seat to object. That would be one way. – lllrnr101 Apr 14 '21 at 13:00

2 Answers2

3

I presume you do not mean to just print the name p3.name.

In case you mean to keep track of all the instances of your class, please refer to: Python: Find Instance of a class by value and How to keep track of class instances?

If I apply the same logic as mentioned in the two references I have quoted above, your code could look something like this:

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")

The get_players_at_seat() function is a class method that returns an iterator containing all players in instances that have their seat property set to the given value of seat. You can then iterate over the iterator and print the names of the players at seat 3.

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
boxhot
  • 189
  • 5
0

The simplest way would be to put all your player objects into a list & loop through the list checking their atributes,

player_list = [p1, p2, p3, p4, p5, p6]

for player in player_list:

    if player.seat == 3:
        print(player.name)
DrBwts
  • 3,470
  • 6
  • 38
  • 62