<p>创建一个<a href="http://greenteapress.com/thinkpython/thinkCSpy/html/chap12.html" rel="nofollow noreferrer">Class</a>是让同一件事“拥有”(或“做”)同一件事的好方法。在</p>
<p>一个常见的类比是工厂:它是一个生成对象模板的对象工厂,然后可以通过属性、角色、职责等对其进行定制</p>
<p>首先,初始化类:</p>
<pre><code>import random
nSuits = 4 # yellow/red/blue/green
nMaxSuits = 10 # only ten of each yellow, red, blue, green
nCards = 25 # Number of random cards
nPlayers = 500
deck = [suit for suit in range(nMaxSuits) for suit in range(nSuits)]
class CardPerson(object):
def __init__(self, cards):
self.cards = cards
def guess(self):
#use [deck] list above, it has all good cards
random.shuffle(self.cards)
return [self.cards.pop() for i in range(nCards)]
if __name__ == '__main__':
for x in range(nPlayers):
person = CardPerson(deck) #you've made your CardPerson...now, get their guesses
#person.guess() will give you 25 guesses
#compare it to the cards variable above; if matches >= 17, then...(???)
</code></pre>
<p>更多信息:</p>
<p>不会使用<code>set</code>s的<a href="https://stackoverflow.com/questions/2727650/common-elements-between-two-lists-not-using-sets-in-python">Getting common elements between two lists</a>(它消除了重复项)。在</p>