Python子类从父类调用方法

时间:2013-12-06 11:26:11

标签: python inheritance python-3.x parent-child subclass

我目前正在自学Python,我接受了关于继承的课程,所以这是我第一次使用子类。我正在学习“Think Python”一书,示例是关于创建代表扑克牌,牌组,牌等的类。以下示例是从本书中复制的(我自己添加了一两个方法,作为练习):

import random
from operator import itemgetter, attrgetter

class Card:
"""represents a standard playing card."""
    def __init__(self, suit=0, rank=2):
        self.suit = suit
        self.rank = rank

    suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
    rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']

    def __str__(self):
        return '%s of %s' % (Card.rank_names[self.rank], Card.suit_names[self.suit])

    def __cmp__(self, other):
        t1 = self.suit, self.rank
        t2 = other.suit, other.rank
        return cmp(t1, t2)

class Deck:
"""represents a standard deck of cards"""
    def __init__(self):
        self.cards = []
        for suit in range(4):
            for rank in range(1, 14):
                card = Card(suit, rank)
                self.cards.append(card)

    def __str__(self):
        res = []
        for card in self.cards:
            res.append(str(card))
        return '\n'.join(res)

    def pop_card(self):
        return self.cards.pop()

    def add_card(self):
        self.cards.append(card)

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

    def sort(self):
        self.cards.sort(key=attrgetter('suit', 'rank'))

class Hand(Deck):
"""represents a hand of playing cards"""
    def __init__(self, label=''):
        self.cards = []
        self.label = label

    def move_cards(self, hand, num):
        for i in range(num):
            hand.add_card(self.pop_card())

我的问题在于Hand子类方法。如果我尝试从Hand子类调用move_cards方法,例如a = Deck()b = Hand(),尝试调用move_cards(b,2),或a.move_cards(b,2)给我相同的{{ 1}}。

为什么会发生这种情况或者我做错了什么?感谢。

1 个答案:

答案 0 :(得分:2)

move_cards仅为子类Hand定义,而不是父类Deck

我认为继承的顺序在示例中令人困惑 - Hand并不真正感觉像是Deck的子类,而是它们都应该是公共卡集合的子类({{1说)。例如(未测试):

Stack

注意子类class Stack: """represents a collection of cards""" def __init__(self): self.cards = [] def __str__(self): res = [] for card in self.cards: res.append(str(card)) return '\n'.join(res) def pop_card(self): return self.cards.pop() def add_card(self): self.cards.append(card) def shuffle(self): random.shuffle(self.cards) def sort(self): self.cards.sort(key=attrgetter('suit', 'rank')) def move_cards(self, dest, num): for i in range(num): dest.add_card(self.pop_card()) class Deck(Stack): """represents a deck of playing cards""" def __init__(self): Stack.__init__(self) for suit in range(4): for rank in range(1, 14): card = Card(suit, rank) self.cards.append(card) class Hand(Stack): """represents a hand of playing cards""" def __init__(self, label=''): Stack.__init__(self) self.label = label Hand的覆盖构造函数如何使用Deck显式调用父构造函数。这会以相同的方式为每个成员初始化Stack.__init__(self)成员。