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.