Home > OS >  Swapping attribute of two instances
Swapping attribute of two instances

Time:11-12

So I am trying to make a turn-based card game, and one of the cards, when played , can swap the hand of the "caster" and the "castee" (not sure if that's even a word). I created a Player class, and instances Jim, Pam, Dwight and Michael. Whenever that card is played I have to swap the hand attribute between two players.

class Player:
    def __init__(self, name, hand=[]):
        self.name = name
        self.hand = [self.draw_card() for n in range(0, 2)]

I've tried creating a method which takes the "castee", which is the self in this case, and swaps hand with the caster, but it doesn't work. Here caster is the name of the other instance, e.g. it could be Michael.hand instead of caster.hand:

def hand_swap(self):
    self.hand, caster.hand = caster.hand, self.hand

I've also tried the following with no luck:

def hand_swap(self):
    myhand = self.hand.copy()
    casterhand = caster.hand.copy()
    setattr(caster, "hand", myhand)
    setattr(self, "hand", casterhand)

After every loop, players and their hands are printed in a dictionary. The code doesn't throw up any errors, but no hand has been swapped and everything remains the same.

Is there something wrong with my code or is it not so straightforward when it comes to having one instance change another instance's attributes?

edit1: what "caster" is edit2: how I check that it fails

CodePudding user response:

If you add caster to hand_swap() you will achieve your goal.

def hand_swap(self, caster):
    self.hand, caster.hand = caster.hand, self.hand

Then to swap hands

pam.hand_swap(michael)
  • Related