Mark
Mark

Reputation: 3738

Is there a way to access the same object from two different objects in Python?

I have been trying to practice python classes by making a card game. Simply put a human player gets to play the computer from the same deck of cards. My question is how do I get the human player and the computer to access the same deck?

I have created a Player class, a Computer class and a Deck Class. The Player Class and the Computer class both inherent the Deck Class. In the Deck class I have a class variable for the "deck". What I have noticed though is if I apply a Deck method to the "deck" class variable and then calls it as an instance of a player, any changes to the "deck" class variable is tied to the player instance and so the computer instance will not be able to access it.

Maybe I've missed something or maybe I am going about the completely wrong, can someone provide some input?

Upvotes: 0

Views: 852

Answers (1)

Kevin
Kevin

Reputation: 76194

The Player Class and the Computer class both inherent the Deck Class

That's not the ideal approach. A class should only inherit from another if the two classes satisfy an "is a" relationship conceptually. For example, Dog should inherit from Animal because a dog is an animal. Player should not inherit from Deck because a player is not a deck.

Instead of inheriting, try making the deck an attribute of the player and computer objects. If the deck object is mutable, then changes to it will be visible from both objects.

class Deck:
    def __init__(self):
        self.cards = ["Pot of Greed", "Black Lotus", "Ace of Spades", "Draw Four"]

class Player:
    def __init__(self, name, deck):
        self.name = name
        self.deck = deck

class Computer:
    def __init__(self, difficulty, deck):
        self.difficulty = difficulty
        self.deck = deck

d = Deck()
p = Player("Steve", d)
c = Computer("Easy", d)

#confirm that the player and computer decks are the same object
print(p.deck is c.deck)

#changes made to the deck via p will be observable from c and vice versa
p.deck.cards.append("How to Play Poker Instruction Card")
print(c.deck.cards)

Upvotes: 1

Related Questions