简体   繁体   English

替换类的列表元素

[英]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]

When you pass a list in python, behind the scenes it is just a ref to this list. 当您在python中传递列表时,在后台仅是对该列表的引用。

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. 另一个解决方案是猴子修补get_card方法,因此定义类本身不会在运行时受到影响,我们将新的实现附加到get_card方法。 If You need this second solution let me know. 如果您需要第二种解决方案,请告诉我。

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 猴子修补get_card函数

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 解决方案2面向对象的方法

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 创建一个派生类并重写get_card方法

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM