【发布时间】:2015-11-20 13:12:03
【问题描述】:
有几本书(或教程)以下列方式定义了一张卡片和一副牌:
import random
class Card(object):
""" A card object with a suit and rank."""
RANKS = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
SUITS = ('Spades', 'Diamonds', 'Hearts', 'Clubs')
def __init__(self, rank, suit):
"""Creates a card with the given rank and suit."""
self.rank = rank
self.suit = suit
def __str__(self):
"""Returns the string representation of a card."""
if self.rank == 1:
rank = 'Ace'
elif self.rank == 11:
rank = 'Jack'
elif self.rank == 12:
rank = 'Queen'
elif self.rank == 13:
rank = 'King'
else:
rank = self.rank
return str(rank) + ' of ' + self.suit
import random
class Deck(object):
""" A deck containing 52 cards."""
def __init__(self):
"""Creates a full deck of cards."""
self._cards = []
for suit in Card.SUITS:
for rank in Card.RANKS:
c = Card(rank, suit)
self._cards.append(c)
def shuffle(self):
"""Shuffles the cards."""
random.shuffle(self._cards)
def deal(self):
"""Removes and returns the top card or None
if the deck is empty."""
if len(self) == 0:
return None
else:
return self._cards.pop(0)
def __len__(self):
"""Returns the number of cards left in the deck."""
return len(self._cards)
def __str__(self):
"""Returns the string representation of a deck."""
result = ''
for c in self._cards:
result = self.result + str(c) + '\n'
return result
我正在阅读的一本最近的书将其定义为:
import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
def __init__(self):
self._cards = [Card(rank, suit) for suit in self.suits
for rank in self.ranks]
def __len__(self):
return len(self._cards)
def __getitem__(self, position):
return self._cards[position]
如果不出意外,这个版本“似乎”不那么冗长。 (但这不是我关心的问题。事实上,比较代码的长度是错误的。)
对于这个例子,也许一般来说,将卡片定义为 namedtuple 与 class 的优缺点是什么?
如果答案只是一个是可变的而另一个不是,我有什么理由关心这个?
一个版本比另一个版本更 Pythonic 吗?
【问题讨论】:
-
A
namedtuple具有不可变的实例,并且可能不包含任何用户定义的函数。一个类可能不是不可变的(至少不是非常不可变),你可以在其中放入一堆有用的函数。
标签: python class python-3.x collections namedtuple