对象列表不可迭代及函数外变量调用

1 投票
1 回答
2025 浏览
提问于 2025-04-18 12:39

我看到过这个帖子,但还是搞不清楚我的问题。关于Python中对象列表的迭代“不可迭代”。我的问题还有第二部分:我怎么能在一个函数中创建的变量在另一个函数中使用呢?我先从这个开始。网上找到的答案有:

第一种方法 - 使用全局变量

def func1():
    global value2,value1
    value1 = 1
    value2 = 2
def func2():
    global value2,value1
    do smth with value1 
    do smth with value2

func1()
func2()

但这不是个好主意,原因有很多。我还不太明白,比如我在使用相同的命名空间,这限制了变量的命名方式。而且一些不可预测的行为更容易出现……(这是我理解的)

第二种方法 - 函数是对象,而Python中的一切都是对象!

def func1():
    func1.value1 = 1
    func1.value2 = 2
def func2():
    do smth with func1.value1
    do smth with func1.value2

func1()
func2()

这算是个更好的主意吗?

第三种方法 - 使用返回值

我知道大家都说:尽量让你的函数返回一些值,以便后续使用。但是!我有一个函数draw(),它每秒要运行60次,所以这样写就很麻烦:

def draw():
    variable = some_function()

我的函数每秒要启动60次,而我只需要在特定的触发/按钮被按下时启动一次。

最后我的主要问题,这是我的代码:

class Card:
    def __init__(self, suit, rank):
        ...
    def draw(self, canvas, pos):
        ...
class Hand:
    def __init__(self):
        self.hand_list = []
    def draw(self, canvas, pos):
        ...
    deff add_card(self)

def deal():
    test_hand = Deck() # from the Deck we fulfill cards to player and computer hands
    test_hand.shuffle()
    deal.player_hand, computer_hand = Hand(), Hand()

def draw(canvas):
    i = 0
    for card in deal.player_hand:
        deal.player_hand.draw(canvas, [300, 300])

最后我得到了。

TypeError: 'Hand'对象不可迭代

某个地方self.hand_list的类型从列表变成了非列表。或者问题出在更深的地方。因为当我查看解释器打印的内容时,它打印了2张某种花色和等级的牌作为1个对象。我不知道该从哪里开始。希望能得到一些建议。

我有《Learning Python》这本书,可能有些主题我应该更深入地研究一下?

谢谢大家!

这是我的代码链接。你可以从那里运行它。http://www.codeskulptor.org/#user35_zXdT3D8RpqJXoVb.py

1 个回答

2

你的问题出在 draw 方法里:

for card in deal.player_hand:
    ...

你在循环 player_hand,这个其实是一个 Hand 类的对象,而不是手里的牌。你可能想用 for card in deal.player_hand.hand_list 这样的写法。

撰写回答