Just-code-it
Just-code-it

Reputation: 51

Replace the list element of class

This is a homework to select a card from cards. After a card being selected, the card in list should be replaced by None.

class Card():
   def __init__(self,cards):
       self._cards = cards

   def get_cards(self):
       return self._cards

   def get_card(self,slot):
       return self._cards[slot]

It is not allowed to change or add any other code for above class.

And the expected output shows below

card1 = Card([1,2,3,4])
# card1.get_cards()=None (I try this but it does not work because it is not allowed to assign item to method)
print(card1.get_card(0)) # expectation: 1
print(card1.get_cards()) # expectation: [None, 2, 3, 4]
print(card1.get_card(1)) # expectation: 2
print(card1.get_cards()) # expectation: [None, None, 3, 4]

Upvotes: 2

Views: 242

Answers (2)

Abdul Gaffar
Abdul Gaffar

Reputation: 390

class Card():
   def __init__(self,cards):
       self._cards = cards

   def get_cards(self):
       return self._cards

   def get_card(self,slot):
       return self._cards[slot]

Monkey patching the get_card function

def get_my_card(self, slot):
    card, self._cards[slot] = self._cards[slot], None
    return card

Time to test the above code

card1 = Card([1,2,3,4])
Card.get_card = get_my_card
print(card1.get_card(0)) # expectation: 1
print(card1.get_cards()) # expectation: [None, 2, 3, 4]
print(card1.get_card(1)) # expectation: 2
print(card1.get_cards()) # expectation: [None, None, 3, 4]

Output

1
[None, 2, 3, 4]
2
[None, None, 3, 4]

Solution 2: Object-Oriented Approach

class Card():    def __init__(self,cards):
        self._cards = cards

    def get_cards(self):
        return self._cards

    def get_card(self,slot):
        return self._cards[slot]

Create a derived class and overrride get_card method

class MyCard(Card):

    def get_card(self, slot):
        card, self._cards[slot] = self._cards[slot], None
        return card

Test the code

card1 = MyCard([1,2,3,4])
print(card1.get_card(0)) # expectation: 1
print(card1.get_cards()) # expectation: [None, 2, 3, 4]
print(card1.get_card(1)) # expectation: 2
print(card1.get_cards()) # expectation: [None, None, 3, 4]

Upvotes: 1

Take_Care_
Take_Care_

Reputation: 2144

When you pass a list in python, behind the scenes it is just a ref to this list.

So we can use this to our advantage here.

# You almost has done it right 
# take the list ref 
cards = card1.get_cards()
# and now mutate the list inside 
cards[slot] = None

The other solution is to monkey patch the get_card method, so the definition class itself won't be affected in the runtime we will attach new implementation to get_card method. If You need this second solution let me know.

Upvotes: 2

Related Questions