前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Python 中方法调用的求值顺序

Python 中方法调用的求值顺序

原创
作者头像
用户11021319
发布2024-04-24 09:11:00
发布2024-04-24 09:11:00
8600
代码可运行
举报
运行总次数:0
代码可运行
  1. 问题背景 在 Python 中,方法调用的求值顺序可能会令人困惑,尤其是当涉及到嵌套方法调用时。例如,在下面的代码中,我们有一个 Card 类,它表示一张扑克牌,一个 Hand 类,它表示一组扑克牌,以及一个 Deck 类,它表示一副扑克牌。
代码语言:python
代码运行次数:0
复制
class Card(object):
    """ A playing card. """
    RANKS = ["A", "2", "3", "4", "5", "6", "7",
             "8", "9", "10", "J", "Q", "K"]
    SUITS = ["c", "d", "h", "s"]

    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        rep = self.rank + self.suit
        return rep

class Hand(object):
    """ A hand of playing cards. """
    def __init__(self):
        self.cards = []

    def __str__(self):
        if self.cards:
           rep = ""
           for card in self.cards:
               rep += str(card) + "\t"
        else:
            rep = "<empty>"
        return rep

    def clear(self):
        self.cards = []

    def add(self, card):
        self.cards.append(card)

    def give(self, card, other_hand):
        self.cards.remove(card)
            other_hand.add(card)


class Deck(Hand):
    """ A deck of playing cards. """

    def populate(self):
        for suit in Card.SUITS:
            for rank in Card.RANKS: 
                self.add(Card(rank, suit))   # <- HERE

    def shuffle(self):
        import random
        random.shuffle(self.cards)

    def deal(self, hands, per_hand = 1):
        for rounds in range(per_hand):
            for hand in hands:
                if self.cards:
                    top_card = self.cards[0]
                    self.give(top_card, hand)
                else:
                    print("Can't continue deal. Out of cards!")


# main
deck1 = Deck()
print("Created a new deck.")
print("Deck:")
print(deck1)

deck1.populate()
print("\nPopulated the deck.")
print("Deck:")
print(deck1)

问题是,在 Deck 类的 populate() 方法中,self.add(Card(rank, suit)) 的求值顺序是什么?Card(rank, suit) 是先被直接发送到 add 方法,还是先被发送到 Card 类,然后再发送到 add 方法?

  1. 解决方案 Card(rank, suit) 是先被发送到 Card 类,然后才被发送到 add 方法。Card(rank, suit) 会创建一个新的 Card 对象,然后这个对象会被作为参数传递给 add 方法。 以下是一些代码示例:
代码语言:python
代码运行次数:0
复制
# 创建一个新的 `Card` 对象
card = Card("A", "c")

# 将 `card` 添加到 `hand`
hand.add(card)

在上面的示例中,Card("A", "c") 会先创建一个新的 Card 对象,然后这个对象会被作为参数传递给 hand.add() 方法。

以下是一些其他代码示例:

代码语言:python
代码运行次数:0
复制
# 创建一个新的 `Card` 对象,并将其直接传递给 `hand.add()` 方法
hand.add(Card("A", "c"))

# 创建一个新的 `Card` 对象,并将其存储在变量 `card` 中
card = Card("A", "c")

# 将 `card` 添加到 `hand`
hand.add(card)

在上面的示例中,Card("A", "c") 仍然会先创建一个新的 Card 对象,然后这个对象会被作为参数传递给 hand.add() 方法。但是,在第二种示例中,card 变量被用作中间变量来存储 Card 对象,然后才将其添加

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档