首页 > 解决方案 > 将列表从另一个类传递给类中的方法,以修改所述列表并传回 Python 中的原始类

问题描述

我正在为我的在线投资组合编写一个新颖的二十一点程序,该程序可以随机创建卡片。

为了不在一轮中创建重复的卡片,我创建了一个列表来存储已经创建的卡片。然后根据 dealed_cards 列表中包含的牌检查新的随机牌,如果重复,则再次调用该方法并分配新牌。

我的 dealed_cards 列表是在一个创建回合的类中启动的,然后作为一个列表从一个类传递到另一个类,该列表可以在新一轮游戏开始时重新初始化。但是,该列表未正确传递到类中分配新卡值的方法中。

我尝试传递列表的一些方法是:(self,dealed_cards),我得到错误

TypeError deal_card_out() missing 1 required positional argument: 'dealed_cards'
With (self, dealed_cards = [], *args) 

这至少有效但不一定正确传递列表,当我尝试在修改它之前从方法中打印出 dealed_cards 列表时,我得到一个空列表。

使用(self, *dealed_cards)这会将列表作为元组返回,并且不会正确传递。最后是(self, dealed_cards = [])结果:仍然没有从函数内部传入列表 dealed_cards

这是我从主程序中断开的代码测试块,以测试此方法。

class deal_card(object):

def __init__(self):
    pass
def deal_card_out(self, dealed_cards = []): 
    print("This is a test print statement at the beginning of this method to test that dealed_cards was passed in correctly.")
    print(dealed_cards)
    card_one_face_value = 'Seven'
    card_one_suit_value = 'Clubs'

    for _ in dealed_cards:
        if card_one_face_value == [_[0]]:
            print(f"This is a test print statement inside the for loop within deal_card out, it willl print out [_[0]] inside this for loop: {[_[0]]}")
            if card_one_suit_value == [_[1]]:
                print("test loop successful")
            else:
                print(f"This is a test print statement inside the for loop within deal_card out, it willl print out [_[0]] inside this for loop: {[_[0]]}") 
                pass
        else:
            print(f"this is a test print statement inside the for loop within deal_card out it will print out dealed_cards[_[1]] to show what is happening inside this loop: {[_[1]]}")
            pass
        dealed_cards.append([card_one_face_value,card_one_suit_value])

        print("This is a test print inside of deal_card_out, it prints list dealed_cards after method modifies the list")
        print(dealed_cards)
        return [dealed_cards,card_one_face_value,card_one_suit_value]

dealed_cards = [['Place','Holder'],['Seven','Clubs']]
print("this is a test print statement outside of the method to test that     dealed_cards is being passed in correctly")
print(dealed_cards)
test_run = deal_card.deal_card_out(dealed_cards)

标签: python-3.xalgorithmoopmethods

解决方案


弄清楚该方法有什么问题。“self”不需要放在方法定义中。出于某种原因,将 self 放入方法调用中并没有正确传递 dealed_cards 列表。此外,dealed_cards 可以作为 dealed_cards 传递,而不是 dealed_cards = []。因此,新的正确方法定义是def deal_card_out(dealed_cards): for 循环也行为不端,if card_one_face_value == [_[0]]:需要将测试语句更改为,if card_one_face_value == _[0]:否则您将使用 7 左右的括号进行测试,即嵌套列表中的字符串。


推荐阅读